/* global React, Spark, Wordmark, useTweaks, TweaksPanel, TweakSection, TweakColor, TweakRadio, TweakToggle, TweakSelect, BlogRouter */
// ============================================================
// SPARKIO — Landing Page
// ============================================================
const { useState, useEffect, useRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "Ember",
  "font": "Geist",
  "theme": "Dark",
  "motion": "Subtle",
  "projects": "Card grid"
}/*EDITMODE-END*/;

const ACCENTS = {
  Ember:   { g1:"#FF6A1A", g2:"#FF8A3D", g3:"#FFC46B", ember:"#FF7A2E", flame:"#FFA23E", glow:"#FFD37A", coal:"#C5471A" },
  Violet:  { g1:"#6D28D9", g2:"#8B5CF6", g3:"#C4B5FD", ember:"#8B5CF6", flame:"#A78BFA", glow:"#C4B5FD", coal:"#5B21B6" },
  Azure:   { g1:"#1D4ED8", g2:"#3B82F6", g3:"#93C5FD", ember:"#3B82F6", flame:"#60A5FA", glow:"#93C5FD", coal:"#1E40AF" },
  Duotone: { g1:"#E11D74", g2:"#FB6F4C", g3:"#FFC46B", ember:"#FB6F4C", flame:"#FF8A5B", glow:"#FFC46B", coal:"#BE185D" },
};
const FONTS = {
  Geist:        "'Geist', system-ui, sans-serif",
  "Space Grotesk": "'Space Grotesk', system-ui, sans-serif",
  Helvetica:    "'Helvetica Neue', Helvetica, Arial, sans-serif",
};

const PROJECTS = [
  ["Founder", "Interactive business history simulator inspired by the stories and decisions behind the world's most influential companies.", "Simulator", "https://founder.sparkio.me/"],
  ["Blest", "Platform for managing language institutes, students, courses and learning operations.", "Education", "https://app.blestlearning.com/"],
  ["Fidelis Church", "Church administration and community management platform.", "Community", "https://fidelischurch.sparkio.me/"],
  ["Fidelis Wealth", "Personal wealth tracking platform for assets, liabilities and financial reporting.", "Fintech", "https://fidelis.sparkio.me/"],
  ["GoPlanify", "Appointment scheduling platform created to simplify booking experiences for businesses and customers.", "Scheduling", "https://www.goplanify.com/"],
  ["AppGrid", "Platform designed to help independent developers connect their products with potential customers.", "Marketplace", "https://appgrid.sparkio.me/"],
  ["Global Prayer", "Spanish-language Christian community for sharing public or private prayer requests and receiving spiritual support in real time.", "Community", "https://prayer.sparkio.me"],
  ["Meal Planner", "Personalized weekly meal plans and shopping lists for families, adapted to dietary needs and Latin American food culture.", "Foodtech", "https://mealplanner.sparkio.me"],
];

// — scroll reveal (data-rv attribute survives React re-renders) —
function useReveal() {
  const ioRef = useRef(null);
  if (!ioRef.current && typeof IntersectionObserver !== "undefined") {
    ioRef.current = new IntersectionObserver((es) => {
      es.forEach((e) => {
        if (e.isIntersecting) { e.target.dataset.rv = "1"; ioRef.current.unobserve(e.target); }
      });
    }, { threshold: 0.12 });
  }
  React.useLayoutEffect(() => {
    document.querySelectorAll(".reveal:not([data-rv])").forEach((el) => {
      if (ioRef.current) ioRef.current.observe(el);
      else el.dataset.rv = "1";
    });
  });
}

function Nav() {
  return (
    <nav className="nav">
      <div className="wrap nav-in">
        <Wordmark size={26} variant="gradient" color="var(--fg)" />
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <a className="ghost" href="/blog" style={{ fontSize: 14, fontWeight: 500 }}>Blog</a>
          <a className="ghost" href="https://github.com/SparkIOme" target="_blank" rel="noopener">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path d="M8 0C3.58 0 0 3.58 0 8a8 8 0 005.47 7.59c.4.07.55-.17.55-.38v-1.34c-2.23.48-2.7-1.07-2.7-1.07-.36-.93-.89-1.18-.89-1.18-.73-.5.05-.49.05-.49.8.06 1.23.83 1.23.83.72 1.23 1.87.87 2.33.66.07-.52.28-.87.5-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.83-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.6 7.6 0 014 0c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.52.56.83 1.28.83 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48v2.2c0 .21.15.46.55.38A8 8 0 0016 8c0-4.42-3.58-8-8-8z"/></svg>
            SparkIOme
          </a>
          <a className="btn btn-primary" href="#projects">See the work</a>
        </div>
      </div>
    </nav>
  );
}

function Hero({ motionOn }) {
  const wrapRef = useRef(null);
  const [p, setP] = useState({ x: 0, y: 0 });
  useEffect(() => {
    if (!motionOn) { setP({ x: 0, y: 0 }); return; }
    const h = (e) => {
      const r = wrapRef.current?.getBoundingClientRect(); if (!r) return;
      setP({ x: (e.clientX - r.left - r.width / 2) / r.width, y: (e.clientY - r.top - r.height / 2) / r.height });
    };
    window.addEventListener("mousemove", h);
    return () => window.removeEventListener("mousemove", h);
  }, [motionOn]);
  const par = (k) => ({ transform: `translate(${p.x * k}px, ${p.y * k}px)` });

  return (
    <header ref={wrapRef} style={{ position: "relative", overflow: "hidden",
      borderBottom: "1px solid var(--line)" }}>
      <div style={{ position: "absolute", inset: 0,
        background: "radial-gradient(70% 70% at 78% 18%, color-mix(in oklab, var(--g2) 16%, transparent), transparent 60%)" }} />
      {/* floating sparks — kept clear of the headline column */}
      <div className="floaty" style={{ position: "absolute", top: "12%", right: "30%", opacity: .5, ...par(-22) }}>
        <Spark variant="gradient" size={22} id="h-s1" /></div>
      <div className="floaty" style={{ position: "absolute", bottom: "12%", left: "5%", opacity: .4, animationDelay: "1.2s", ...par(-14) }}>
        <Spark variant="gradient" size={15} id="h-s2" /></div>
      <div className="floaty" style={{ position: "absolute", top: "24%", right: "8%", opacity: .5, animationDelay: ".6s", ...par(18) }}>
        <Spark variant="gradient" size={18} id="h-s3" /></div>

      <div className="wrap" style={{ position: "relative", display: "grid",
        gridTemplateColumns: "1.15fr .85fr", gap: 40, alignItems: "center",
        minHeight: "min(82vh, 720px)", padding: "80px 32px" }}>
        <div>
          <div className="eyebrow reveal">Small projects. Big curiosity.</div>
          <h1 style={{ fontSize: "clamp(48px, 8vw, 104px)", fontWeight: 800, letterSpacing: "-0.05em",
            lineHeight: .92, margin: "22px 0 0" }} className="reveal">
            Turning <span style={{ background: "var(--ember-grad)", WebkitBackgroundClip: "text",
              backgroundClip: "text", color: "transparent" }}>sparks</span><br />into products.
          </h1>
          <p className="reveal" style={{ fontSize: "clamp(17px,2.2vw,21px)", color: "var(--fg-2)",
            maxWidth: 480, lineHeight: 1.5, margin: "26px 0 0", transitionDelay: ".05s" }}>
            We build software, automation tools, learning platforms, and experiments that solve real problems.
          </p>
          <div className="reveal" style={{ display: "flex", gap: 14, marginTop: 34, flexWrap: "wrap", transitionDelay: ".1s" }}>
            <a className="btn btn-primary" href="#projects">Explore projects
              <span className="arrow">→</span></a>
            <a className="btn btn-ghost" href="#philosophy">Our philosophy</a>
          </div>
        </div>
        <div style={{ display: "flex", justifyContent: "center", ...par(10) }}>
          <div className="pulseglow drift" style={{ filter: "drop-shadow(0 20px 60px color-mix(in oklab, var(--g1) 38%, transparent))" }}>
            <Spark variant="twotone" size={340} id="h-main" />
          </div>
        </div>
      </div>
    </header>
  );
}

function Philosophy() {
  const steps = ["Build.", "Learn.", "Launch.", "Repeat."];
  const [active, setActive] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setActive((a) => (a + 1) % 4), 1500);
    return () => clearInterval(t);
  }, []);
  const lines = ["Some ideas become products.", "Some become experiments.", "Some fail.", "All of them teach us something."];
  return (
    <section id="philosophy" style={{ borderBottom: "1px solid var(--line)" }}>
      <div className="wrap" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 56,
        padding: "100px 32px", alignItems: "center" }}>
        <div className="reveal">
          <div className="eyebrow" style={{ marginBottom: 26 }}>Philosophy</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            {steps.map((s, i) => (
              <span key={s} style={{ fontSize: "clamp(40px,6vw,72px)", fontWeight: 800, letterSpacing: "-0.04em",
                lineHeight: 1.0, color: active === i ? "transparent" : "var(--fg)",
                background: active === i ? "var(--ember-grad)" : "none",
                WebkitBackgroundClip: active === i ? "text" : "border-box", backgroundClip: active === i ? "text" : "border-box",
                opacity: active === i ? 1 : .32, transition: "opacity .5s, color .5s" }}>{s}</span>
            ))}
          </div>
        </div>
        <div className="reveal" style={{ transitionDelay: ".1s" }}>
          {lines.map((l, i) => (
            <div key={i} style={{ display: "flex", gap: 16, alignItems: "baseline",
              padding: "18px 0", borderTop: i ? "1px solid var(--line)" : "none" }}>
              <Spark variant="solid" size={13} id={`ph-${i}`} strokeColor="var(--ember)" style={{ flexShrink: 0, transform: "translateY(2px)" }} />
              <span style={{ fontSize: "clamp(19px,2.4vw,26px)", fontWeight: 500, letterSpacing: "-0.02em",
                color: i === lines.length - 1 ? "var(--fg)" : "var(--fg-2)" }}>{l}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function ProjectsGrid() {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(300px, 1fr))", gap: 18 }}>
      {PROJECTS.map(([n, d, tag, url], i) => (
        <a className="proj-card reveal" key={i} href={url} target="_blank" rel="noopener noreferrer"
          style={{ transitionDelay: `${i * 0.05}s`, textDecoration: "none", color: "inherit" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
            <Spark variant="gradient" size={28} id={`pc-${i}`} />
            <span className="mono" style={{ fontSize: 11, color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: ".08em" }}>{tag}</span>
          </div>
          <h3 style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em", margin: "6px 0 0" }}>{n}</h3>
          <p style={{ fontSize: 14.5, color: "var(--fg-2)", lineHeight: 1.5, margin: 0, flex: 1 }}>{d}</p>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 7, color: "var(--ember)", fontWeight: 600, fontSize: 14, marginTop: 4 }}>
            View <span className="arrow">↗</span></span>
        </a>
      ))}
    </div>
  );
}

function ProjectsList() {
  return (
    <div>
      {PROJECTS.map(([n, d, tag, url], i) => (
        <a className="proj-row reveal" key={i} href={url} target="_blank" rel="noopener noreferrer"
          style={{ transitionDelay: `${i * 0.04}s`, textDecoration: "none", color: "inherit" }}>
          <span className="mono" style={{ fontSize: 12, color: "var(--fg-3)" }}>0{i + 1}</span>
          <span style={{ display: "flex", alignItems: "center", gap: 12, fontSize: "clamp(18px,2.4vw,24px)", fontWeight: 600, letterSpacing: "-0.02em" }}>
            <Spark variant="gradient" size={18} id={`pl-${i}`} />{n}</span>
          <span className="rowdesc" style={{ fontSize: 14.5, color: "var(--fg-2)", lineHeight: 1.4 }}>{d}</span>
          <span className="arrow" style={{ color: "var(--ember)", fontSize: 18, justifySelf: "end" }}>↗</span>
        </a>
      ))}
    </div>
  );
}

function ProjectsBento() {
  const spans = ["span 2", "span 1", "span 1", "span 1", "span 1", "span 2", "span 1", "span 1"];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gridAutoRows: "minmax(180px,auto)", gap: 18 }}>
      {PROJECTS.map(([n, d, tag, url], i) => {
        const feat = i === 0 || i === 5;
        return (
          <a className="proj-card reveal" key={i} href={url} target="_blank" rel="noopener noreferrer"
            style={{ gridColumn: spans[i], transitionDelay: `${i * 0.05}s`, textDecoration: "none",
            background: feat ? "var(--ember-grad)" : "var(--bg-2)", border: feat ? "none" : "1px solid var(--line)",
            color: feat ? "#1A0E04" : "var(--fg)", justifyContent: "space-between" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
              <Spark variant={feat ? "solid" : "gradient"} size={28} id={`pb-${i}`} strokeColor={feat ? "#1A0E04" : undefined} />
              <span className="mono" style={{ fontSize: 11, opacity: .7, textTransform: "uppercase", letterSpacing: ".08em" }}>{tag}</span>
            </div>
            <div>
              <h3 style={{ fontSize: feat ? 26 : 21, fontWeight: 600, letterSpacing: "-0.02em", margin: "0 0 6px" }}>{n}</h3>
              <p style={{ fontSize: 14, lineHeight: 1.45, margin: 0, opacity: feat ? .85 : 1, color: feat ? "#1A0E04" : "var(--fg-2)" }}>{d}</p>
            </div>
          </a>
        );
      })}
    </div>
  );
}

function Projects({ layout }) {
  return (
    <section id="projects" style={{ borderBottom: "1px solid var(--line)" }}>
      <div className="wrap" style={{ padding: "100px 32px" }}>
        <div className="reveal" style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end",
          flexWrap: "wrap", gap: 16, marginBottom: 44 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 16 }}>Projects</div>
            <h2 style={{ fontSize: "clamp(34px,5vw,56px)", fontWeight: 800, letterSpacing: "-0.04em", margin: 0 }}>
              Things we've built.</h2>
          </div>
          <span style={{ color: "var(--fg-2)", fontSize: 15, maxWidth: 320, lineHeight: 1.5 }}>
            Some shipped. Some still cooking. Each one started as a spark.</span>
        </div>
        {layout === "Editorial list" ? <ProjectsList /> : layout === "Bento" ? <ProjectsBento /> : <ProjectsGrid />}
      </div>
    </section>
  );
}

function Closing() {
  return (
    <section style={{ position: "relative", overflow: "hidden", borderBottom: "1px solid var(--line)" }}>
      <div style={{ position: "absolute", inset: 0,
        background: "radial-gradient(60% 80% at 50% 120%, color-mix(in oklab, var(--g1) 20%, transparent), transparent 60%)" }} />
      <Spark variant="gradient" size={40} id="cl-1" style={{ position: "absolute", top: "20%", left: "16%", opacity: .3 }} className="floaty" />
      <Spark variant="gradient" size={24} id="cl-2" style={{ position: "absolute", top: "60%", right: "18%", opacity: .35 }} className="floaty" />
      <div className="wrap reveal" style={{ position: "relative", padding: "130px 32px", textAlign: "center",
        display: "flex", flexDirection: "column", alignItems: "center", gap: 26 }}>
        <Spark variant="twotone" size={104} id="cl-main" className="pulseglow" />
        <h2 style={{ fontSize: "clamp(30px,4.6vw,52px)", fontWeight: 700, letterSpacing: "-0.035em",
          lineHeight: 1.08, maxWidth: 760, margin: 0, textWrap: "balance" }}>
          We believe creativity is no longer limited by technical barriers. Ideas can move faster than ever.</h2>
        <p style={{ fontSize: "clamp(17px,2.2vw,21px)", color: "var(--fg-2)", maxWidth: 560, lineHeight: 1.5, margin: 0 }}>
          Sparkio exists to explore what happens when curiosity, software and AI come together.</p>
        <a className="btn btn-primary" href="https://github.com/SparkIOme" target="_blank" rel="noopener" style={{ marginTop: 6 }}>
          Follow along<span className="arrow">→</span></a>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer>
      <div className="wrap" style={{ padding: "56px 32px", display: "flex", justifyContent: "space-between",
        alignItems: "flex-end", flexWrap: "wrap", gap: 28 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 12, maxWidth: 320 }}>
          <Wordmark size={24} variant="gradient" color="var(--fg)" />
          <span style={{ color: "var(--fg-2)", fontSize: 14.5, lineHeight: 1.5 }}>Building products, experiments and ideas.</span>
        </div>
        <div style={{ display: "flex", gap: 48, flexWrap: "wrap" }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <span className="mono" style={{ fontSize: 11, color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: ".1em" }}>Site</span>
            <a href="https://sparkio.me" target="_blank" rel="noopener" style={{ color: "var(--fg)", textDecoration: "none", fontSize: 14.5 }}>sparkio.me</a>
            <a href="https://github.com/SparkIOme" target="_blank" rel="noopener" style={{ color: "var(--fg)", textDecoration: "none", fontSize: 14.5 }}>GitHub · SparkIOme</a>
            <a href="https://medium.com/@diegoezce" target="_blank" rel="noopener" style={{ color: "var(--fg)", textDecoration: "none", fontSize: 14.5 }}>Medium · @diegoezce</a>
            <a href="https://www.linkedin.com/in/diego-cervera" target="_blank" rel="noopener" style={{ color: "var(--fg)", textDecoration: "none", fontSize: 14.5 }}>LinkedIn · Diego Cervera</a>
          </div>
        </div>
      </div>
      <div className="wrap" style={{ padding: "20px 32px 40px", borderTop: "1px solid var(--line)",
        display: "flex", justifyContent: "space-between", color: "var(--fg-3)", fontSize: 13, flexWrap: "wrap", gap: 8 }}>
        <span>© {new Date().getFullYear()} Sparkio</span>
        <span className="mono">build · learn · launch · repeat</span>
      </div>
    </footer>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useReveal();
  const a = ACCENTS[t.accent] || ACCENTS.Ember;
  const motionOn = t.motion !== "Off";
  const rootStyle = {
    "--g1": a.g1, "--g2": a.g2, "--g3": a.g3,
    "--ember": a.ember, "--flame": a.flame, "--glow": a.glow, "--coal": a.coal,
    "--font-sans": FONTS[t.font] || FONTS.Geist,
  };
  const cls = `page ${t.theme === "Light" ? "light" : ""} ${motionOn ? "m-on" : ""} ${t.motion === "Lively" ? "m-lively" : ""}`;

  const isBlog = window.location.pathname === '/blog' || window.location.pathname.startsWith('/blog/');

  if (isBlog) {
    return (
      <div className={cls} style={rootStyle}>
        <BlogRouter />
      </div>
    );
  }

  return (
    <div className={cls} style={rootStyle}>
      <Nav />
      <Hero motionOn={motionOn} />
      <Philosophy />
      <Projects layout={t.projects} />
      <Closing />
      <Footer />

      <TweaksPanel>
        <TweakSection label="Brand" />
        <TweakColor label="Accent" value={a.ember}
          options={[ACCENTS.Ember.ember, ACCENTS.Violet.ember, ACCENTS.Azure.ember, ACCENTS.Duotone.ember]}
          onChange={(v) => {
            const name = Object.keys(ACCENTS).find((k) => ACCENTS[k].ember === v) || "Ember";
            setTweak("accent", name);
          }} />
        <TweakSelect label="Typeface" value={t.font} options={["Geist", "Space Grotesk", "Helvetica"]}
          onChange={(v) => setTweak("font", v)} />
        <TweakRadio label="Theme" value={t.theme} options={["Dark", "Light"]}
          onChange={(v) => setTweak("theme", v)} />
        <TweakSection label="Layout & motion" />
        <TweakSelect label="Projects" value={t.projects} options={["Card grid", "Editorial list", "Bento"]}
          onChange={(v) => setTweak("projects", v)} />
        <TweakRadio label="Motion" value={t.motion} options={["Off", "Subtle", "Lively"]}
          onChange={(v) => setTweak("motion", v)} />
      </TweaksPanel>
    </div>
  );
}

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