/* ============================================================
   Sections
   ============================================================ */
const PD = window.PD;

/* ---------------- Status marquee ---------------- */
function StatusBar() {
  const items = PD.status;
  const group = (
    <div className="marquee-group">
      {items.map((s, i) => <span key={i} className="status-item">{s}</span>)}
    </div>
  );
  return (
    <div className="statusbar">
      <div className="marquee">{group}{group}</div>
    </div>
  );
}

/* ---------------- Nav ---------------- */
function Clock() {
  const [t, setT] = useState("");
  useEffect(() => {
    const fmt = () => new Date().toLocaleTimeString("en-US", { timeZone: "America/El_Salvador", hour: "2-digit", minute: "2-digit", hour12: false });
    setT(fmt());
    const id = setInterval(() => setT(fmt()), 1000 * 20);
    return () => clearInterval(id);
  }, []);
  return <span className="nav-clock"><span className="dot" />SAN SALVADOR {t}</span>;
}

function Nav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener("scroll", onScroll, { passive: true }); onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const links = [["Work", "#work"], ["About", "#about"], ["Services", "#services"], ["Contact", "#contact"]];
  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
      <div className="wrap nav-inner">
        <a className="brand" href="#top" data-cursor="hot">
          <span className="brand-mark">ML</span>
          <span>Miguel&nbsp;Ledezma</span>
        </a>
        <div className="nav-links">
          {links.map(([l, h]) => <a key={l} className="nav-link" href={h}>{l}</a>)}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
          <span className="nav-clock" style={{ }}><Clock /></span>
          <Pill variant="lime" ico="↗" href="#contact" magnetic={false}>Let's talk</Pill>
        </div>
      </div>
    </nav>
  );
}

/* ---------------- Hero ---------------- */
function HeroBlob() {
  // blocky organic blob echoing the reference, in lime
  return (
    <svg className="blob" viewBox="0 0 520 480" fill="none" aria-hidden="true">
      <defs>
        <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0" stopColor="#c2f24a" stopOpacity="0.95" />
          <stop offset="1" stopColor="#7fae2c" stopOpacity="0.8" />
        </linearGradient>
      </defs>
      <path fill="url(#bg)" d="M120 40h150v40h60v-40h70v90h60v120h40v110h-60v80h-90v-50h-70v50H170v-70h-60v-90H60V180h60V40Z" />
    </svg>
  );
}

function HeroTerminal() {
  const lines = PD.term;
  const [shown, setShown] = useState(0);
  useEffect(() => {
    let i = 0;
    const id = setInterval(() => {
      i++; setShown(i);
      if (i >= lines.length) {
        clearInterval(id);
        setTimeout(() => { i = 0; setShown(0); }, 2600);
        // restart loop
        setTimeout(() => {
          const id2 = setInterval(() => { i++; setShown(i); if (i >= lines.length) clearInterval(id2); }, 520);
        }, 2900);
      }
    }, 520);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="glasswin">
      <div className="win-bar">
        <span className="win-dot" style={{ background: "#ff5f57" }} />
        <span className="win-dot" style={{ background: "#febc2e" }} />
        <span className="win-dot" style={{ background: "#28c840" }} />
        <span className="win-title">~/deploy — zsh</span>
      </div>
      <div className="win-body">
        {lines.slice(0, shown).map((l, i) => (
          <div className="tline" key={i}>
            {l.p ? (<><span className="tprompt">{l.p} ❯</span> {l.t}</>) : (
              <><span className="tdim">{l.o}</span><span className={l.k === "done" ? "tok" : "tok"}>{l.k === "done" ? "" : "OK"}</span></>
            )}
          </div>
        ))}
        {shown < lines.length && <span className="cursor" />}
      </div>
    </div>
  );
}

function Hero() {
  const words = PD.hero.headline;
  return (
    <header className="hero wrap" id="top">
      <div className="hero-grid">
        <div>
          <Reveal><span className="eyebrow">{PD.hero.eyebrow}</span></Reveal>
          <h1 className="h-display">
            {words.map((w, i) => w === "\n"
              ? <br key={i} />
              : <span className="word" key={i}
                  style={{ marginRight: "0.26em", animationDelay: `${0.15 + i * 0.05}s`, color: (w === "AI" || w === "themselves.") ? "var(--lime)" : undefined }}>
                  {w}
                </span>
            )}
          </h1>
          <Reveal delay={0.5}><p className="hero-sub">{PD.hero.sub}</p></Reveal>
          <Reveal delay={0.6}>
            <div className="hero-cta">
              <Pill variant="lime" ico="↗" href="#work">View my work</Pill>
              <Pill variant="ghost" ico="↗" href={PD.github}>GitHub</Pill>
            </div>
          </Reveal>
        </div>

        <div className="hero-visual">
          <HeroBlob />
          <div className="term-float" style={{ position: "relative", zIndex: 2, width: "100%", display: "grid", placeItems: "center" }}>
            <HeroTerminal />
          </div>
          <div className="float-card fc-1 floaty">
            <span className="fc-ico">✓</span>
            <span><b>6 deployments</b><small>web · mobile · live</small></span>
          </div>
          <div className="float-card fc-2 floaty alt">
            <span className="fc-ico" style={{ background: "transparent", color: "var(--lime)", border: "1px solid var(--lime)" }}>AI</span>
            <span><b>Claude · PyTorch</b><small>orchestration + vision</small></span>
          </div>
        </div>
      </div>

      <div className="techstrip">
        <div className="techstrip-inner">
          {[...PD.tech, ...PD.tech].map((t, i) => <span className="tech-item" key={i}>{t}</span>)}
        </div>
      </div>
    </header>
  );
}

/* ---------------- Metrics ---------------- */
function Metrics() {
  return (
    <section className="metrics" aria-label="Key metrics">
      {PD.metrics.map((m, i) => (
        <Reveal key={i} delay={i * 0.08} className="metric">
          <div className="num"><Counter to={m.num} suffix={m.suf} decimals={m.num % 1 !== 0 ? 1 : 0} /></div>
          <div className="lbl">{m.lbl}</div>
        </Reveal>
      ))}
    </section>
  );
}

/* ---------------- About ---------------- */
function About() {
  return (
    <section className="section" id="about">
      <div className="wrap">
        <Reveal><span className="eyebrow">About</span></Reveal>
        <div className="about-grid" style={{ marginTop: 34 }}>
          <Reveal y={30}>
            <div className="about-photo">
              <div className="photo-tag">📍 San Salvador, El Salvador</div>
              <image-slot id="miguel-photo" shape="rounded" radius="0" placeholder="Drop your photo here"></image-slot>
            </div>
          </Reveal>
          <div>
            <Reveal delay={0.1}>
              <p className="about-statement" dangerouslySetInnerHTML={{ __html: PD.about.statement }} />
            </Reveal>
            {PD.about.body.map((p, i) => (
              <Reveal key={i} delay={0.15 + i * 0.08}><p className="about-body">{p}</p></Reveal>
            ))}
            <Reveal delay={0.3}>
              <dl className="facts">
                {PD.about.facts.map((f, i) => (
                  <div className="fact" key={i}><dt>{f.k}</dt><dd>{f.v}</dd></div>
                ))}
              </dl>
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Services ---------------- */
function Services() {
  return (
    <section className="section" id="services" style={{ background: "var(--bg-2)", borderBlock: "1px solid var(--line)" }}>
      <div className="wrap">
        <div className="sec-head">
          <div>
            <Reveal><span className="eyebrow">What I do</span></Reveal>
            <Reveal delay={0.05}><h2 className="h-display" style={{ marginTop: 18 }}>From idea<br />to live deployment.</h2></Reveal>
          </div>
          <Reveal delay={0.1}><p className="lead">Three ways I help founders and teams turn manual, repetitive work into software that runs itself.</p></Reveal>
        </div>
        <Reveal y={26}>
          <div className="svc-list">
            {PD.services.map((s, i) => (
              <div className="svc" key={i} data-cursor="hot">
                <span className="svc-no">0{i + 1}</span>
                <div>
                  <div className="svc-title">{s.title}</div>
                  <div className="svc-tags">{s.tags.map((t) => <span className="tag" key={t}>{t}</span>)}</div>
                </div>
                <div className="svc-desc">{s.desc}</div>
                <span className="svc-arrow">↗</span>
              </div>
            ))}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------------- Project visuals (generative motifs) ---------------- */
function RouteVisual({ hue }) {
  return (
    <div className="proj-canvas" style={{ background: `radial-gradient(120% 120% at 70% 10%, hsl(${hue} 70% 16%), #0c0d09 70%)` }}>
      <svg viewBox="0 0 320 220" style={{ width: "100%", height: "100%" }}>
        <path d="M30 180 C 90 120, 120 150, 170 90 S 260 50, 290 40" fill="none" stroke={`hsl(${hue} 80% 55%)`} strokeWidth="2.5" strokeDasharray="7 7" />
        {[[30,180],[170,90],[290,40]].map((p,i)=>(<circle key={i} cx={p[0]} cy={p[1]} r="6" fill={`hsl(${hue} 85% 60%)`} />))}
        <circle r="5" fill="#0c0d09" stroke={`hsl(${hue} 90% 65%)`} strokeWidth="2.5">
          <animateMotion dur="3.4s" repeatCount="indefinite" keyPoints="0;1;0" keyTimes="0;0.5;1" calcMode="spline" keySplines="0.4 0 0.2 1;0.4 0 0.2 1" path="M30 180 C 90 120, 120 150, 170 90 S 260 50, 290 40" />
        </circle>
        <rect x="244" y="20" width="64" height="34" rx="7" fill="rgba(0,0,0,.45)" stroke={`hsl(${hue} 60% 40%)`} />
        <text x="276" y="41" textAnchor="middle" fontFamily="monospace" fontSize="11" fill={`hsl(${hue} 80% 70%)`}>MATCHED</text>
      </svg>
    </div>
  );
}
function GridVisual({ hue }) {
  return (
    <div className="proj-canvas" style={{ background: `radial-gradient(120% 120% at 30% 10%, hsl(${hue} 55% 15%), #0a0c0a 70%)`, padding: 22, display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 10 }}>
      {Array.from({ length: 6 }).map((_, i) => (
        <div key={i} className="gridcell" style={{ borderRadius: 10, background: "rgba(255,255,255,.05)", border: `1px solid hsl(${hue} 40% 30%)`, padding: 9, animationDelay: `${i * 0.25}s` }}>
          <div style={{ width: "60%", height: 6, borderRadius: 4, background: `hsl(${hue} 70% 55%)`, marginBottom: 7 }} />
          <div style={{ width: "85%", height: 5, borderRadius: 4, background: "rgba(255,255,255,.14)" }} />
        </div>
      ))}
    </div>
  );
}
function ChartVisual({ hue }) {
  const bars = [42, 70, 55, 88, 64, 96];
  return (
    <div className="proj-canvas" style={{ background: `radial-gradient(120% 120% at 70% 10%, hsl(${hue} 65% 16%), #0d0b08 70%)`, display: "flex", alignItems: "flex-end", gap: 12, padding: "26px 24px" }}>
      {bars.map((h, i) => (
        <div key={i} className="chartbar" style={{ flex: 1, height: `${h}%`, background: i === bars.length - 1 ? `hsl(${hue} 85% 58%)` : "rgba(255,255,255,.12)", borderRadius: "6px 6px 0 0", animationDelay: `${i * 0.08}s` }} />
      ))}
    </div>
  );
}
function ProjVisual({ i, hue }) {
  if (i === 0) return <RouteVisual hue={hue} />;
  if (i === 1) return <GridVisual hue={hue} />;
  return <ChartVisual hue={hue} />;
}

/* ---------------- Projects ---------------- */
function Projects() {
  return (
    <section className="section" id="work">
      <div className="wrap">
        <div className="sec-head">
          <div>
            <Reveal><span className="eyebrow">Selected work</span></Reveal>
            <Reveal delay={0.05}><h2 className="h-display" style={{ marginTop: 18 }}>Things I've shipped.</h2></Reveal>
          </div>
          <Reveal delay={0.1}><p className="lead">Six production deployments for government, enterprise and startup clients. A few I can show.</p></Reveal>
        </div>
        <div className="proj-track">
          {PD.projects.map((p, i) => (
            <Reveal key={i} delay={i * 0.1} y={28}>
              <article className="proj" data-cursor="hot">
                <div className="proj-media">
                  <ProjVisual i={i} hue={p.hue} />
                  <span className="proj-cat">{p.cat}</span>
                  <span className="proj-num">0{i + 1}/0{PD.projects.length}</span>
                </div>
                <div className="proj-body">
                  <div className="proj-title">{p.title}<span className="ar">↗</span></div>
                  <p className="proj-desc">{p.desc}</p>
                  <div className="proj-foot">
                    <span className="proj-metric">◆ {p.metric}</span>
                    <span className="proj-stack">{p.stack.map((s) => <span key={s}>{s}</span>)}</span>
                  </div>
                </div>
              </article>
            </Reveal>
          ))}
        </div>
        <Reveal delay={0.1}>
          <div style={{ display: "flex", justifyContent: "center", marginTop: 44 }}>
            <Pill variant="dark" ico="↗" href={PD.github}>See more on GitHub — @{PD.githubHandle}</Pill>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------------- Contact ---------------- */
function CtaMarquee() {
  const word = (
    <span className="cta-word"><b>Let's build something</b><span className="star">✦</span></span>
  );
  return (
    <div className="cta-marquee" aria-hidden="true">
      <div className="cta-marquee-inner">{word}{word}{word}{word}{word}{word}</div>
    </div>
  );
}

function Contact() {
  const links = [
    { i: "@", b: "Email", s: PD.email, h: `mailto:${PD.email}` },
    { i: "GH", b: "GitHub", s: "@" + PD.githubHandle, h: PD.github },
    { i: "in", b: "LinkedIn", s: "Miguel Ledezma", h: PD.linkedin },
    { i: "▶", b: "itch.io", s: "miorlear — games", h: PD.itch },
  ];
  return (
    <section className="section" id="contact">
      <div className="wrap">
        <div className="contact-grid contact">
          <div>
            <Reveal><span className="eyebrow">Contact</span></Reveal>
            <Reveal delay={0.05}>
              <h2 className="h-display" style={{ marginTop: 18 }}>Have a workflow<br />worth <span className="lime">automating?</span></h2>
            </Reveal>
            <Reveal delay={0.1}>
              <p className="hero-sub" style={{ maxWidth: "44ch", marginTop: 22 }}>
                I'm open to freelance projects, client work, and internships. Tell me what's slowing your team down — I'll help you replace it with software.
              </p>
            </Reveal>
            <Reveal delay={0.15}>
              <div className="hero-cta">
                <Pill variant="lime" ico="↗" href={`mailto:${PD.email}`}>Email me</Pill>
                <Pill variant="ghost" ico="↗" href={PD.linkedin}>LinkedIn</Pill>
              </div>
            </Reveal>
          </div>
          <Reveal delay={0.15} y={26}>
            <div className="contact-links">
              {links.map((l) => (
                <a className="clink" key={l.b} href={l.h} data-cursor="hot" target="_blank" rel="noreferrer">
                  <span className="ci">{l.i}</span>
                  <span className="ct"><b>{l.b}</b><small>{l.s}</small></span>
                  <span className="ca">↗</span>
                </a>
              ))}
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="wrap footer-inner">
        <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
          <span className="brand-mark">ML</span>
          <small>© {new Date().getFullYear()} Miguel Ledezma — Built with care in San Salvador.</small>
        </div>
        <div className="footer-nav">
          <a href="#work">Work</a><a href="#about">About</a><a href="#services">Services</a>
          <a href={PD.github}>GitHub</a><a href={PD.linkedin}>LinkedIn</a>
        </div>
      </div>
    </footer>
  );
}

/* ---------------- App ---------------- */
function App() {
  return (
    <>
      <Cursor />
      <Progress />
      <StatusBar />
      <Nav />
      <main>
        <Hero />
        <Metrics />
        <About />
        <Services />
        <Projects />
        <CtaMarquee />
        <Contact />
      </main>
      <Footer />
    </>
  );
}

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