/* global React, ReactDOM, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakColor, TweakToggle */
const { useState, useEffect, useRef } = React;

/* ---------- inline line icons (functional UI iconography) ---------- */
const I = {
  sun: <g><circle cx="12" cy="12" r="4.2"/><path d="M12 2.5v2.6M12 18.9v2.6M21.5 12h-2.6M5.1 12H2.5M18.4 5.6l-1.8 1.8M7.4 16.6l-1.8 1.8M18.4 18.4l-1.8-1.8M7.4 7.4 5.6 5.6"/></g>,
  chat: <g><path d="M4 5.5h16v11H9l-4 3.5v-3.5H4z"/><path d="M8.5 10h7M8.5 13h4"/></g>,
  chart: <g><path d="M4 4v16h16"/><path d="M8 14l3.2-3.6L14 13l4-5"/></g>,
  link: <g><path d="M9.5 14.5l5-5"/><path d="M8.2 11.5 6 13.7a3.1 3.1 0 0 0 4.4 4.4l2.2-2.2"/><path d="M15.8 12.5 18 10.3a3.1 3.1 0 0 0-4.4-4.4l-2.2 2.2"/></g>,
  gauge: <g><path d="M4.5 17a8 8 0 1 1 15 0"/><path d="M12 13l3.5-3"/><circle cx="12" cy="13" r="1.2"/></g>,
  layers: <g><path d="M12 3.5 3.5 8 12 12.5 20.5 8 12 3.5z"/><path d="M3.5 12 12 16.5 20.5 12M3.5 16 12 20.5 20.5 16"/></g>,
  bolt: <g><path d="M13 2.5 5 13.5h6l-1 8 8-11h-6z"/></g>,
  shield: <g><path d="M12 3l7 3v5c0 4.4-3 8-7 10-4-2-7-5.6-7-10V6z"/><path d="M9 12l2 2 4-4.5"/></g>,
  globe: <g><circle cx="12" cy="12" r="8.5"/><path d="M3.5 12h17M12 3.5c2.4 2.3 3.6 5.3 3.6 8.5S14.4 18.2 12 20.5C9.6 18.2 8.4 15.2 8.4 12S9.6 5.8 12 3.5z"/></g>,
  arrow: <g><path d="M5 12h14M13 6l6 6-6 6"/></g>,
};
function Icon({ name, cls }) {
  return (
    <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      {I[name]}
    </svg>
  );
}

/* ---------- scroll reveal ---------- */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver((ents) => {
      ents.forEach((e) => { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } });
    }, { threshold: 0.16 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

/* ---------- animated counter ---------- */
function Counter({ to, suffix = "", dur = 1500 }) {
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  useEffect(() => {
    let raf, started = false;
    const io = new IntersectionObserver((ents) => {
      if (ents[0].isIntersecting && !started) {
        started = true;
        const t0 = performance.now();
        const tick = (t) => {
          const p = Math.min(1, (t - t0) / dur);
          const e = 1 - Math.pow(1 - p, 3);
          setVal(Math.round(e * to));
          if (p < 1) raf = requestAnimationFrame(tick);
        };
        raf = requestAnimationFrame(tick);
      }
    }, { threshold: 0.5 });
    if (ref.current) io.observe(ref.current);
    return () => { io.disconnect(); cancelAnimationFrame(raf); };
  }, [to, dur]);
  return <span ref={ref} className="num">{val}<span className="suf">{suffix}</span></span>;
}

/* ---------- EU emblem (12 stars) ---------- */
function EuStars() {
  const stars = [];
  for (let i = 0; i < 12; i++) {
    const a = (i / 12) * Math.PI * 2 - Math.PI / 2;
    const cx = 32 + Math.cos(a) * 13.5, cy = 21.5 + Math.sin(a) * 13.5;
    stars.push(<text key={i} x={cx} y={cy + 2.4} fontSize="6.4" textAnchor="middle" fill="#FFCC00" fontFamily="serif">★</text>);
  }
  return <svg className="stars" viewBox="0 0 64 43" role="img" aria-label="European Union emblem"><rect width="64" height="43" rx="3" fill="#003399"/>{stars}</svg>;
}
const FlagHR = () => (
  <svg className="flag" viewBox="0 0 30 20" aria-label="Croatia"><rect width="30" height="6.66" fill="#ff0000"/><rect y="6.66" width="30" height="6.66" fill="#fff"/><rect y="13.33" width="30" height="6.67" fill="#171796"/></svg>
);
const FlagRS = () => (
  <svg className="flag" viewBox="0 0 30 20" aria-label="Serbia"><rect width="30" height="6.66" fill="#c6363c"/><rect y="6.66" width="30" height="6.66" fill="#0c4076"/><rect y="13.33" width="30" height="6.67" fill="#fff"/></svg>
);

/* ============================ HERO ============================ */
function Hero({ style }) {
  return (
    <header className="hero" data-style={style} id="top">
      <div className="hero-bg"></div>
      <div className="grid-tex"></div>
      <div className="glow" style={{ width: 460, height: 460, background: "var(--accent)", top: "-12%", right: "-6%" }}></div>
      <div className="glow" style={{ width: 360, height: 360, background: "var(--amber)", bottom: "-14%", left: "-8%", opacity: .22 }}></div>
      <div className="hero-content">
        <div className="wrap">
          <div className="hero-text">
            <span className="eyebrow">AI-powered solar adoption · HR ⟷ RS</span>
            <h1 className="hero-h1">The intelligent guide to <span className="hl">going solar</span> across the border.</h1>
            <p className="hero-sub">SAIEMM Assistant turns the complex journey of solar adoption into clear, data-driven steps — sizing, savings, regulation and trusted installers — built on real installation data from the Croatia–Serbia region.</p>
            <div className="hero-actions">
              <a href="#contact" className="btn btn-primary">Get notified at launch <Icon name="arrow"/></a>
              <a href="#features" className="btn btn-ghost">Explore the platform</a>
            </div>
            <div className="hero-trust"><span className="dot"></span> Currently in Work Package 1 · requirements & research phase</div>
          </div>
          <div className="hero-figure">
            <div className="frame"></div>
            <div className="hero-chip c1">
              <div className="ic"><Icon name="sun"/></div>
              <div><div className="v">Solar potential</div><div className="k">assessed by AI</div></div>
            </div>
            <div className="hero-chip c2">
              <div className="ic"><Icon name="chart"/></div>
              <div><div className="v">Real ROI data</div><div className="k">regional installs</div></div>
            </div>
          </div>
        </div>
      </div>
    </header>
  );
}

/* ============================ STATS ============================ */
const STATS = [
  { to: 2, suf: "", lab: "Countries connected", sub: "Croatia · Serbia" },
  { to: 3, suf: "", lab: "Languages supported", sub: "HR / SR / EN" },
  { to: 4, suf: "", lab: "Stakeholder groups served", sub: "adopters → operators" },
  { to: 100, suf: "%", lab: "Data-driven guidance", sub: "real installations" },
];
function Stats() {
  return (
    <section className="stats">
      <div className="wrap">
        <div className="stats-grid">
          {STATS.map((s, i) => (
            <div className="stat reveal" data-d={i + 1} key={i}>
              <Counter to={s.to} suffix={s.suf} />
              <div className="lab">{s.lab}</div>
              <div className="sub">{s.sub}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============================ FEATURES ============================ */
const FEATURES = [
  { ic: "chat", t: "AI adoption assistant", d: "A natural-language guide that breaks technical complexity into understandable steps — personalised to your location, consumption and budget.", tag: "Guidance" },
  { ic: "chart", t: "Data-driven decisions", d: "Cost-benefit and ROI projections grounded in actual performance data from comparable installations across the region.", tag: "Analysis" },
  { ic: "link", t: "Smart installer matching", d: "Get matched with qualified installers by expertise, proximity and track record — with standardised, comparable quotes.", tag: "Marketplace" },
  { ic: "gauge", t: "Monitoring & optimisation", d: "Continuous performance analysis, anomaly detection and AI recommendations that keep installed systems running at their best.", tag: "Operations" },
  { ic: "layers", t: "Regional knowledge base", d: "A growing, privacy-preserving record of how solar performs under real regional conditions — improving every new prediction.", tag: "Intelligence" },
  { ic: "globe", t: "Cross-border standardisation", d: "Shared best practices and unified processes that bridge the regulatory and market differences between the two countries.", tag: "Cooperation" },
];
function Features() {
  const onMove = (e) => {
    const r = e.currentTarget.getBoundingClientRect();
    e.currentTarget.style.setProperty("--mx", `${e.clientX - r.left}px`);
    e.currentTarget.style.setProperty("--my", `${e.clientY - r.top}px`);
  };
  return (
    <section className="sec-pad" id="features">
      <div className="wrap">
        <div className="sec-head reveal">
          <span className="eyebrow">What it does</span>
          <h2>One platform across the whole solar journey.</h2>
          <p>From the first question to long-term optimisation — SAIEMM supports adopters, installers and existing owners with intelligence built for the cross-border region.</p>
        </div>
        <div className="feat-grid">
          {FEATURES.map((f, i) => (
            <article className="card reveal" data-d={(i % 3) + 1} key={i} onMouseMove={onMove}>
              <div className="icon"><Icon name={f.ic}/></div>
              <h3>{f.t}</h3>
              <p>{f.d}</p>
              <div className="tag">{f.tag}</div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============================ PROJECT ============================ */
const POINTS = [
  { n: "01", h: "A real cross-border challenge", p: "Croatia and Serbia share climate, market dynamics and a fast-growing appetite for solar — but face fragmented regulation, data and installer ecosystems." },
  { n: "02", h: "An AI-first response", p: "SAIEMM unifies guidance, real installation data and installer matching into a single intelligent assistant available in all three regional languages." },
  { n: "03", h: "Research before build", p: "During Work Package 1, requirements are validated through stakeholder interviews and analysis — ensuring the system reflects genuine regional needs." },
];
function Project() {
  return (
    <section className="project sec-pad" id="project">
      <div className="wrap">
        <div className="proj-grid">
          <div className="reveal">
            <span className="eyebrow">The project</span>
            <h2 className="sec-head" style={{ fontSize: "clamp(30px,4.4vw,52px)", marginTop: 16 }}>Accelerating solar adoption, together.</h2>
            <div className="proj-points">
              {POINTS.map((p) => (
                <div className="proj-point" key={p.n}>
                  <div className="n">{p.n}</div>
                  <div><h4>{p.h}</h4><p>{p.p}</p></div>
                </div>
              ))}
            </div>
          </div>
          <div className="xb reveal" data-d="2">
            <div className="xb-title">Cross-border region</div>
            <div className="xb-countries">
              <div className="xb-c"><FlagHR/><div className="cn">Croatia</div><div className="cd">Regulation · grid · incentives</div></div>
              <div className="xb-link"><Icon name="link"/></div>
              <div className="xb-c"><FlagRS/><div className="cn">Serbia</div><div className="cd">Regulation · grid · incentives</div></div>
            </div>
            <p className="xb-note">A shared knowledge base lets best practices, performance insights and optimisation strategies flow freely between both markets — building a more unified, efficient regional solar economy.</p>
            <div className="glow" style={{ width: 240, height: 240, background: "var(--accent)", bottom: "-30%", right: "-10%", opacity: .3 }}></div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================ FUNDING ============================ */
function Funding() {
  return (
    <section className="funding sec-pad" id="partners">
      <div className="wrap">
        <div className="sec-head reveal" style={{ marginBottom: 40 }}>
          <span className="eyebrow">Partners & funding</span>
          <h2>Backed by cross-border cooperation.</h2>
        </div>
        <div className="fund-card reveal" data-d="1">
          <div className="fund-logos">
            <div className="eu-emblem">
              <EuStars/>
              <div className="cap">Co-funded by the European Union</div>
            </div>
            <div className="interreg">
              <div className="ig-mark"><span style={{background:"var(--sky)"}}></span><span style={{background:"var(--amber)"}}></span><span style={{background:"var(--green)"}}></span></div>
              <div className="ig-txt"><div className="ig-name">interreg</div><div className="ig-sub">IPA Croatia–Serbia</div></div>
            </div>
          </div>
          <div className="fund-text">
            <p>SAIEMM is developed within the Interreg IPA cross-border cooperation programme, advancing renewable-energy adoption and digital innovation across the Croatia–Serbia region.</p>
            <p className="disc">This output reflects the views only of the project, and the programme authorities cannot be held responsible for any use that may be made of the information contained therein.</p>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================ FOOTER ============================ */
function Footer() {
  // status: idle | sending | ok | error
  const [status, setStatus] = useState("idle");
  const submit = async (e) => {
    e.preventDefault();
    const form = e.currentTarget;
    const email = form.email.value.trim();
    if (!email) return;
    setStatus("sending");
    try {
      const res = await fetch("submit.php", {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: new URLSearchParams({ email, website: form.website.value }),
      });
      const data = await res.json().catch(() => ({ ok: false }));
      if (res.ok && data.ok) { setStatus("ok"); form.reset(); }
      else setStatus("error");
    } catch (_) {
      setStatus("error");
    }
  };
  return (
    <footer className="footer" id="contact">
      <div className="wrap">
        <div className="foot-grid">
          <div className="foot-brand">
            <div className="brand"><span className="mark"><Icon name="bolt"/></span> SAIEMM</div>
            <p>The AI assistant accelerating solar power adoption across the Croatia–Serbia cross-border region.</p>
            <form className="contact-row" onSubmit={submit}>
              <input type="email" name="email" required placeholder="your@email.com" aria-label="Email address"/>
              {/* honeypot — bots fill this, humans never see it */}
              <input type="text" name="website" tabIndex="-1" autoComplete="off" aria-hidden="true" className="hp"/>
              <button className="btn btn-primary" type="submit" disabled={status === "sending"}>
                {status === "sending" ? "Sending…" : "Notify me"}
              </button>
            </form>
            <div className={"contact-msg" + (status === "ok" ? " show ok" : "")}>✓ Thanks — we'll be in touch at launch.</div>
            <div className={"contact-msg" + (status === "error" ? " show err" : "")}>Couldn't send just now — please email <a href="mailto:hello@saiemm.eu">hello@saiemm.eu</a>.</div>
          </div>
          <div className="foot-col">
            <h5>Explore</h5>
            <a href="#features">Platform</a>
            <a href="#project">The project</a>
            <a href="#partners">Partners & funding</a>
            <a href="#top">Back to top</a>
          </div>
          <div className="foot-col">
            <h5>Contact</h5>
            <a href="mailto:hello@saiemm.eu">hello@saiemm.eu</a>
            <span className="li">Croatia · Serbia</span>
            <span className="li">Work Package 1 — 2026</span>
          </div>
        </div>
        <div className="foot-bottom">
          <div className="copy">© 2026 SAIEMM · Interreg IPA Croatia–Serbia</div>
          <div className="mini"><a href="#">Privacy</a><a href="#">Accessibility</a><a href="#contact">Contact</a></div>
        </div>
      </div>
    </footer>
  );
}

/* ============================ NAV ============================ */
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 24);
    on(); window.addEventListener("scroll", on);
    return () => window.removeEventListener("scroll", on);
  }, []);
  return (
    <nav className={"nav" + (scrolled ? " scrolled" : "")}>
      <div className="wrap nav-inner">
        <a href="#top" className="brand"><span className="mark"><Icon name="bolt"/></span> SAIEMM</a>
        <div className="nav-links">
          <a href="#features">Platform</a>
          <a href="#project">Project</a>
          <a href="#partners">Partners</a>
          <a href="#contact">Contact</a>
        </div>
        <div className="nav-cta">
          <span className="lang-pill">EN</span>
          <a href="#contact" className="btn btn-primary" style={{ padding: "11px 20px" }}>Get notified</a>
        </div>
      </div>
    </nav>
  );
}

/* ============================ APP ============================ */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroStyle": "fullbleed",
  "accent": "green",
  "texture": true
}/*EDITMODE-END*/;

const ACCENTS = {
  sky:   { c: "#0ea5e9", b: "#38bdf8", s: "rgba(14,165,233,0.16)" },
  amber: { c: "#f59e0b", b: "#fbbf24", s: "rgba(245,158,11,0.16)" },
  green: { c: "#10b981", b: "#34d399", s: "rgba(16,185,129,0.16)" },
};

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useReveal();

  useEffect(() => {
    const a = ACCENTS[t.accent] || ACCENTS.sky;
    const r = document.documentElement.style;
    r.setProperty("--accent", a.c);
    r.setProperty("--accent-bright", a.b);
    r.setProperty("--accent-soft", a.s);
  }, [t.accent]);

  useEffect(() => {
    document.body.classList.toggle("no-texture", !t.texture);
  }, [t.texture]);

  return (
    <React.Fragment>
      <Nav/>
      <Hero style={t.heroStyle}/>
      <Stats/>
      <Features/>
      <Project/>
      <Funding/>
      <Footer/>

      <TweaksPanel>
        <TweakSection label="Hero" />
        <TweakRadio label="Hero style" value={t.heroStyle}
          options={[{value:"fullbleed",label:"Full-bleed"},{value:"spotlight",label:"Spotlight"},{value:"split",label:"Split"}]}
          onChange={(v) => setTweak("heroStyle", v)} />
        <TweakSection label="Theme" />
        <TweakColor label="Accent" value={ACCENTS[t.accent].c}
          options={[ACCENTS.sky.c, ACCENTS.amber.c, ACCENTS.green.c]}
          onChange={(v) => {
            const key = Object.keys(ACCENTS).find((k) => ACCENTS[k].c === v) || "sky";
            setTweak("accent", key);
          }} />
        <TweakToggle label="Grid texture" value={t.texture} onChange={(v) => setTweak("texture", v)} />
      </TweaksPanel>
    </React.Fragment>
  );
}

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