// Projects index page

const { useState, useEffect, useRef, useMemo } = React;

function ThreeMini({ variant, autorotate = true }) {
  const ref = useRef(null);
  useEffect(() => {
    let ctrl;
    let alive = true;
    (async () => {
      // Wait until the preloaded agri-scene lib exists
      while (!window.AgriScene || !window.THREE) { await new Promise(r => setTimeout(r, 30)); }
      if (!alive || !ref.current) return;
      ctrl = await window.AgriScene.buildAgriScene({ el: ref.current, variant, autorotate, interactive: false });
    })();
    return () => { alive = false; if (ctrl) ctrl.dispose(); };
  }, [variant]);
  return <div ref={ref} className="threeview" style={{ width: "100%", height: "100%" }} />;
}

function variantFromType(type) {
  return { agri_sheep: "sheep", agri_crops: "crops", agri_vine: "vine", agri_orchard: "orchard" }[type] || "sheep";
}

function CountryFlag({ code }) {
  return <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.08em", color: "var(--am-ink-soft)" }}>{code}</span>;
}

function StatusDot({ status }) {
  const color = { operational: "#6fa764", construction: "#e8823a", development: "#8aa1b6" }[status];
  return <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: 999, background: color, flexShrink: 0 }} />;
}

function ProjectCard({ p, lang }) {
  const typeLabel = t(lang, `type.${p.type}`);
  const statusLabel = t(lang, `status.${p.status}`);
  return (
    <a href={`project.html?id=${p.id}`} className="project-card">
      <div style={{ position: "relative", height: 240, background: "#dfe6e9", overflow: "hidden" }}>
        <ThreeMini variant={variantFromType(p.type)} />
        <div style={{ position: "absolute", top: 14, left: 14, display: "flex", gap: 8 }}>
          <span className="tag orange">{typeLabel}</span>
        </div>
        <div style={{ position: "absolute", bottom: 14, left: 14, display: "flex", alignItems: "center", gap: 8, background: "rgba(255,255,255,0.92)", backdropFilter: "blur(6px)", padding: "5px 10px", borderRadius: 2, fontSize: 11, fontWeight: 600, color: "var(--am-slate-ink)", letterSpacing: "0.06em" }}>
          <StatusDot status={p.status} />
          {statusLabel.toUpperCase()}
        </div>
      </div>
      <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 16 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
          <div>
            <div style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--am-ink-soft)", fontWeight: 600, marginBottom: 6 }}>{p.region}</div>
            <h3 style={{ margin: 0, fontSize: 22, fontWeight: 600, letterSpacing: "-0.015em", color: "var(--am-slate-ink)" }}>{p.name}</h3>
          </div>
          <div className="card-arrow" style={{ width: 34, height: 34, borderRadius: 2, display: "grid", placeItems: "center", border: "1px solid var(--am-border)", color: "var(--am-ink-soft)", transition: "all .2s" }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
          </div>
        </div>
        <div className="hair" />
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
          <div>
            <div style={{ fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--am-ink-soft)", fontWeight: 600 }}>{t(lang, "card.capacity")}</div>
            <div style={{ marginTop: 6, fontSize: 20, fontWeight: 400, letterSpacing: "-0.02em", color: "var(--am-slate-ink)", fontVariantNumeric: "tabular-nums" }}>{p.capacityMW}<span style={{ fontSize: 12, color: "var(--am-ink-soft)", marginLeft: 3 }}>MWc</span></div>
          </div>
          <div>
            <div style={{ fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--am-ink-soft)", fontWeight: 600 }}>{t(lang, "card.area")}</div>
            <div style={{ marginTop: 6, fontSize: 20, fontWeight: 400, letterSpacing: "-0.02em", color: "var(--am-slate-ink)", fontVariantNumeric: "tabular-nums" }}>{p.hectares}<span style={{ fontSize: 12, color: "var(--am-ink-soft)", marginLeft: 3 }}>ha</span></div>
          </div>
          <div>
            <div style={{ fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--am-ink-soft)", fontWeight: 600 }}>{t(lang, "card.commissioned")}</div>
            <div style={{ marginTop: 6, fontSize: 20, fontWeight: 400, letterSpacing: "-0.02em", color: "var(--am-slate-ink)", fontVariantNumeric: "tabular-nums" }}>{p.commissioned}</div>
          </div>
        </div>
      </div>
    </a>
  );
}

function HeroSection({ lang }) {
  return (
    <section style={{ position: "relative", background: "var(--am-slate)", color: "white", overflow: "hidden" }}>
      <div className="grid-overlay" style={{ position: "absolute", inset: 0, opacity: 0.9 }} />
      {/* ambient glow */}
      <div style={{ position: "absolute", top: "-20%", right: "-10%", width: 600, height: 600, borderRadius: "50%", background: "radial-gradient(circle, rgba(232,130,58,0.35), transparent 60%)", filter: "blur(40px)" }} />
      <div style={{ position: "relative", maxWidth: 1400, margin: "0 auto", padding: "96px 48px 72px", display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 72, alignItems: "center" }}>
        <div>
          <div className="eyebrow" style={{ color: "var(--am-orange)" }}>{t(lang, "hero.eyebrow")}</div>
          <h1 style={{ margin: "22px 0 0", fontSize: 62, lineHeight: 1.05, letterSpacing: "-0.025em", fontWeight: 600, color: "white" }}>
            {t(lang, "hero.title")}<br />
            <span className="font-serif" style={{ color: "rgba(255,255,255,0.85)", fontSize: 62 }}>{t(lang, "hero.titleEm")}</span>
          </h1>
          <p style={{ marginTop: 28, fontSize: 17.5, lineHeight: 1.65, color: "rgba(255,255,255,0.8)", maxWidth: 560 }}>{t(lang, "hero.lead")}</p>
          <div style={{ marginTop: 36, display: "flex", gap: 14, flexWrap: "wrap" }}>
            <a className="btn btn-primary" href="#projects">{t(lang, "hero.cta1")}<span>→</span></a>
            <a className="btn btn-light" href="#">{t(lang, "hero.cta2")}</a>
          </div>
        </div>
        {/* Hero 3D */}
        <div style={{ position: "relative", height: 420, border: "1px solid rgba(255,255,255,0.15)", borderRadius: 2 }}>
          <div style={{ position: "absolute", inset: 0 }}>
            <ThreeMini variant="sheep" autorotate={true} />
          </div>
          <div style={{ position: "absolute", top: 14, left: 14, fontSize: 10.5, letterSpacing: "0.22em", textTransform: "uppercase", fontWeight: 600, color: "white", background: "rgba(28,47,63,0.6)", padding: "5px 10px", borderRadius: 2, backdropFilter: "blur(6px)" }}>
            {lang === "fr" ? "Vue 3D en direct" : "Live 3D view"}
          </div>
          <div style={{ position: "absolute", bottom: 14, right: 14, fontSize: 10.5, color: "rgba(255,255,255,0.7)" }}>
            {lang === "fr" ? "Faites pivoter sur la fiche projet →" : "Rotate on the project page →"}
          </div>
        </div>
      </div>

      {/* Totals bar */}
      <div style={{ position: "relative", borderTop: "1px solid rgba(255,255,255,0.12)" }}>
        <div style={{ maxWidth: 1400, margin: "0 auto", padding: "0 48px", display: "grid", gridTemplateColumns: "repeat(4, 1fr)" }}>
          {[
            { k: t(lang, "totals.total"), v: "148", u: "MWc" },
            { k: t(lang, "totals.projects"), v: "32", u: "" },
            { k: t(lang, "totals.hectares"), v: "410", u: "ha" },
            { k: t(lang, "totals.co2"), v: "44 300", u: "" },
          ].map((s, i) => (
            <div key={i} style={{ padding: "32px 24px", borderLeft: i === 0 ? "none" : "1px solid rgba(255,255,255,0.12)" }}>
              <div style={{ fontSize: 42, fontWeight: 300, letterSpacing: "-0.03em", color: "white", fontVariantNumeric: "tabular-nums" }}>{s.v}<span style={{ fontSize: 16, color: "rgba(255,255,255,0.6)", marginLeft: 6 }}>{s.u}</span></div>
              <div style={{ marginTop: 8, fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "rgba(255,255,255,0.6)", fontWeight: 600 }}>{s.k}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function FilterBar({ lang, filter, setFilter }) {
  const types = ["all", "agri_sheep", "agri_crops", "agri_vine", "agri_orchard"];
  return (
    <div className="filter-bar">
      {types.map(tp => (
        <button
          key={tp}
          className={`filter-chip ${filter === tp ? "active" : ""}`}
          onClick={() => setFilter(tp)}
        >
          {tp === "all" ? t(lang, "filters.all") : t(lang, `type.${tp}`)}
        </button>
      ))}
    </div>
  );
}

function IndexApp() {
  const [lang, setLang] = useLang();
  const [filter, setFilter] = useState("all");
  const list = useMemo(() => filter === "all" ? PROJECTS : PROJECTS.filter(p => p.type === filter), [filter]);

  return (
    <div>
      <SiteHeader active="projets" lang={lang} setLang={setLang} />
      <HeroSection lang={lang} />

      <section id="projects" style={{ maxWidth: 1400, margin: "0 auto", padding: "96px 48px 48px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 48, gap: 32, flexWrap: "wrap" }}>
          <div style={{ maxWidth: 640 }}>
            <div className="section-label">{lang === "fr" ? "Portfolio" : "Portfolio"}</div>
            <h2 style={{ margin: 0, fontSize: 40, letterSpacing: "-0.02em", fontWeight: 600, color: "var(--am-slate-ink)", border: "none", padding: 0 }}>{t(lang, "sectionProjectsTitle")}</h2>
            <p style={{ marginTop: 16, fontSize: 16.5, lineHeight: 1.65, color: "var(--am-ink-soft)" }}>{t(lang, "sectionProjectsLead")}</p>
          </div>
          <FilterBar lang={lang} filter={filter} setFilter={setFilter} />
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(380px, 1fr))", gap: 24 }}>
          {list.map(p => <ProjectCard key={p.id} p={p} lang={lang} />)}
        </div>
      </section>

      {/* Map/inline CTA strip */}
      <section style={{ background: "var(--am-muted-bg)", borderTop: "1px solid var(--am-border)", borderBottom: "1px solid var(--am-border)", padding: "72px 48px", position: "relative" }}>
        <div className="grid-overlay-dark" style={{ position: "absolute", inset: 0 }} />
        <div style={{ position: "relative", maxWidth: 1400, margin: "0 auto", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 72, alignItems: "center" }}>
          <div>
            <div className="section-label">{lang === "fr" ? "Implantations" : "Footprint"}</div>
            <h3 style={{ margin: "0 0 12px", fontSize: 32, letterSpacing: "-0.02em", fontWeight: 600, color: "var(--am-slate-ink)" }}>
              {lang === "fr" ? "Présents dans 7 pays, ancrés dans chaque territoire" : "Operating in 7 countries, rooted in every territory"}
            </h3>
            <p style={{ color: "var(--am-ink-soft)", fontSize: 16, lineHeight: 1.65, maxWidth: 520 }}>
              {lang === "fr"
                ? "France, Maroc, Espagne, Portugal, Irlande, Kazakhstan, Vietnam. Plus de 2 000 exploitants agricoles partenaires, 320 collectivités partenaires."
                : "France, Morocco, Spain, Portugal, Ireland, Kazakhstan, Vietnam. Over 2,000 partner farmers, 320 partner local authorities."}
            </p>
            <div style={{ marginTop: 28, display: "flex", gap: 14 }}>
              <a className="btn btn-primary" href="#">{lang === "fr" ? "Nous contacter" : "Get in touch"}<span>→</span></a>
            </div>
          </div>
          <div className="map-frame" style={{ height: 320, border: "1px solid var(--am-border)", position: "relative" }}>
            <svg viewBox="0 0 400 320" style={{ width: "100%", height: "100%" }}>
              {/* Stylized coastline sketch */}
              <path d="M40 120 Q90 80 150 100 T260 110 Q310 90 360 130 L380 200 Q340 240 270 230 Q200 260 130 240 Q70 220 40 180 Z"
                fill="none" stroke="var(--am-slate)" strokeWidth="1" opacity="0.3" strokeDasharray="3 3" />
              <path d="M60 150 Q120 130 180 140 T300 160" fill="none" stroke="var(--am-slate)" strokeWidth="1" opacity="0.25" />
              {/* Project pins */}
              {[
                { x: 170, y: 160, name: "Mas de Nicolas" },
                { x: 145, y: 175, name: "Domaine Saint-Clair" },
                { x: 160, y: 170, name: "Ferme des Garrigues" },
                { x: 180, y: 155, name: "Verger du Luberon" },
                { x: 130, y: 220, name: "Khouribga" },
                { x: 140, y: 130, name: "Nohant" },
              ].map((pin, i) => (
                <g key={i}>
                  <circle cx={pin.x} cy={pin.y} r="10" fill="var(--am-orange)" opacity="0.2" />
                  <circle cx={pin.x} cy={pin.y} r="4" fill="var(--am-orange)" />
                </g>
              ))}
            </svg>
          </div>
        </div>
      </section>

      <SiteFooter lang={lang} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<IndexApp />);
