/* Homepage sections + scroll-reveal helper. Static styles live in home.css;
   only dynamic state-driven styles (Reveal opacity/transform) stay inline. */

const MM1Assembly = () => {
  const containerRef = React.useRef(null);
  const instanceRef = React.useRef(null);
  React.useEffect(() => {
    const container = containerRef.current;
    if (!container) return;
    let cancelled = false;
    let inst;
    const tryStart = () => {
      if (cancelled) return;
      if (!window.MimAssembly) { setTimeout(tryStart, 50); return; }
      inst = window.MimAssembly(container, { url: "assets/M1.glb" });
      instanceRef.current = inst;
      const io = new IntersectionObserver((entries) => {
        for (const e of entries) {
          if (e.isIntersecting) { inst.play(); io.disconnect(); break; }
        }
      }, { threshold: 0.35 });
      io.observe(container);
      instanceRef.current.__io = io;
    };
    tryStart();
    return () => {
      cancelled = true;
      if (instanceRef.current?.__io) instanceRef.current.__io.disconnect();
      if (instanceRef.current?.dispose) instanceRef.current.dispose();
    };
  }, []);
  return (
    <div
      ref={containerRef}
      className="mr-mm1-canvas"
      role="img"
      aria-label="Mimino M1 — VTOL hybrid unmanned aerial vehicle, 3D model"
    />
  );
};

const Reveal = ({ children, delay = 0, as: Tag = "div", className, style, ...rest }) => {
  const ref = React.useRef(null);
  const [visible, setVisible] = React.useState(false);
  React.useEffect(() => {
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce) { setVisible(true); return; }
    const io = new IntersectionObserver(
      (entries) => entries.forEach(e => { if (e.isIntersecting) { setVisible(true); io.disconnect(); }}),
      { threshold: 0.12, rootMargin: "0px 0px -10% 0px" }
    );
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return (
    <Tag ref={ref} className={className} style={{
      opacity: visible ? 1 : 0,
      transform: visible ? "translateY(0)" : "translateY(20px)",
      transition: `opacity 800ms cubic-bezier(0.22,0.61,0.36,1) ${delay}ms, transform 800ms cubic-bezier(0.22,0.61,0.36,1) ${delay}ms`,
      ...style
    }} {...rest}>{children}</Tag>
  );
};

/* ── Buttons ──────────────────────────────────── */
const BtnPrimary = ({ to, children }) => (
  <RLink to={to} className="mr-btn-primary">{children}</RLink>
);
const BtnGhost = ({ to, children }) => (
  <RLink to={to} className="mr-btn-ghost">{children}</RLink>
);

/* ── Hero ─────────────────────────────────────── */
const Hero = () => {
  const { lang } = useT();
  const h = window.MR.home.hero;
  return (
    <section className="mr-home-hero">
      <div className="mr-home-hero__inner">
        <div className="mr-home-hero__text">
          <Reveal delay={0}>
            <span className="eyebrow">{h.eyebrow[lang]}</span>
          </Reveal>
          <Reveal delay={120} as="h1" className="mr-home-hero__title">
            {h.headline[lang]}
          </Reveal>
          <Reveal delay={240} as="p" className="mr-home-hero__sub">
            {h.sub[lang]}
          </Reveal>
          <Reveal delay={340} className="mr-home-hero__actions">
            <BtnPrimary to="/about">{h.primary[lang]}</BtnPrimary>
            <BtnGhost   to="/contact">{h.secondary[lang]}</BtnGhost>
          </Reveal>
        </div>
        <div className="mr-home-hero__model">
          <MM1Assembly />
        </div>
      </div>
    </section>
  );
};

/* ── Sectors ──────────────────────────────────── */
const Sectors = () => {
  const { lang } = useT();
  const s = window.MR.home.sectors;
  return (
    <section className="mr-home-sectors">
      <div className="mr-container">
        <Reveal>
          <span className="eyebrow">{s.eyebrow[lang]}</span>
          <h2 className="mr-home-sectors__title">{s.title[lang]}</h2>
        </Reveal>
        <div className="mr-home-sectors__grid">
          {s.items.map((it, idx) => (
            <Reveal key={it.id} delay={idx * 100} className="mr-home-sector-card">
              <div className="mr-home-sector-card__top">
                <span className="mr-home-sector-card__numeral">{it.numeral}</span>
                <SectorGlyph id={it.id}/>
              </div>
              <h3 className="mr-home-sector-card__title">
                {it[lang === "ka" ? "ka" : "en"]}
              </h3>
              <div className="mr-home-sector-card__sub">
                {it[lang === "ka" ? "subKa" : "subEn"]}
              </div>
              <p className="mr-home-sector-card__body">
                {it[lang === "ka" ? "bodyKa" : "bodyEn"]}
              </p>
              <RLink to={`/sectors#${it.id}`} className="mr-link">{s.learn[lang]}</RLink>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
};

/* Tiny pen-and-ink glyph per sector */
const SectorGlyph = ({ id }) => {
  const ink = "var(--color-ink)";
  const props = { fill: "none", stroke: ink, strokeWidth: 1, strokeLinecap: "round" };
  if (id === "military") return (
    <svg width="40" height="40" viewBox="0 0 40 40" {...props}>
      <circle cx="20" cy="20" r="13" {...props}/>
      <line x1="20" y1="3"  x2="20" y2="11" {...props}/>
      <line x1="20" y1="29" x2="20" y2="37" {...props}/>
      <line x1="3"  y1="20" x2="11" y2="20" {...props}/>
      <line x1="29" y1="20" x2="37" y2="20" {...props}/>
      <circle cx="20" cy="20" r="1.6" fill={ink} stroke="none"/>
    </svg>
  );
  if (id === "agriculture") return (
    <svg width="40" height="40" viewBox="0 0 40 40" {...props}>
      <path d="M 20 5 C 14 12 14 20 20 28" {...props}/>
      <path d="M 20 12 C 26 14 28 18 26 22" {...props}/>
      <circle cx="16" cy="22" r="2" {...props}/>
      <circle cx="20" cy="25" r="2" {...props}/>
      <circle cx="24" cy="22" r="2" {...props}/>
      <circle cx="18" cy="28" r="2" {...props}/>
      <circle cx="22" cy="28" r="2" {...props}/>
      <circle cx="20" cy="32" r="2" {...props}/>
    </svg>
  );
  if (id === "education") return (
    <svg width="40" height="40" viewBox="0 0 40 40" {...props}>
      <path d="M 6 12 C 12 10 18 11 20 14 C 22 11 28 10 34 12 L 34 30 C 28 28 22 29 20 32 C 18 29 12 28 6 30 Z" {...props}/>
      <line x1="20" y1="14" x2="20" y2="32" {...props}/>
    </svg>
  );
  return null;
};

/* ── About preview ─────────────────────────────── */
const AboutPreview = () => {
  const { lang } = useT();
  const a = window.MR.home.about;
  return (
    <section className="mr-home-about">
      <div className="mr-container">
        <Reveal>
          <span className="eyebrow">{a.eyebrow[lang]}</span>
          <p className="mr-home-about__line">{a.line[lang]}</p>
        </Reveal>
        <Reveal delay={120}>
          <p className="mr-home-about__body">{a.body[lang]}</p>
          <RLink to="/about" className="mr-link">{a.cta[lang]}</RLink>
        </Reveal>
      </div>
    </section>
  );
};

/* ── Journal preview ───────────────────────────── */
const JournalPreview = () => {
  const { lang } = useT();
  const j = window.MR.home.journal;
  return (
    <section className="mr-home-journal">
      <div className="mr-container">
        <Reveal>
          <div className="mr-home-journal__head">
            <div>
              <span className="eyebrow">{j.eyebrow[lang]}</span>
              <h2 className="mr-home-journal__title">{j.title[lang]}</h2>
            </div>
            <RLink to="/journal" className="mr-link mr-home-journal__cta">{j.all[lang]}</RLink>
          </div>
        </Reveal>
        <div className="mr-home-journal__grid">
          {j.entries.map((e, i) => (
            <Reveal key={i} delay={i * 100} className="mr-home-journal-entry">
              <div className="mr-home-journal-entry__date">{e.date}</div>
              <h3 className="mr-home-journal-entry__title">
                {lang === "ka" ? e.titleKa : e.titleEn}
              </h3>
              <p className="mr-home-journal-entry__excerpt">
                {lang === "ka" ? e.excerptKa : e.excerptEn}
              </p>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ── Composed Home ─────────────────────────────── */
const PageHome = () => (
  <main>
    <Hero/>
    <Sectors/>
    <AboutPreview/>
    <JournalPreview/>
  </main>
);

window.PageHome = PageHome;
