// HOME page — feature hub
function HomePage({ onNavigate, onOpenTemplate }) {
  const templates = useTemplates();
  return (
    <div className="fade-in">
      {/* HERO */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", flexWrap: "wrap", gap: 24 }}>
        <div>
          <div className="eyebrow">FLEXXI · MARKETING STUDIO</div>
          <h1 className="page-title">
            Ship assets faster,<br />stay on brand.
          </h1>
          <p className="page-subtitle">
            Pick a template. Generate from a Notion brief. Lock the brand. Three ways to make every social asset feel like it came from the same studio.
          </p>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 16, alignItems: "flex-end" }}>
          <button className="btn btn-primary btn-lg" onClick={() => onNavigate("/generate")}>
            <Icons.Wand size={14} /> Generate from scratch
          </button>
        </div>
      </div>

      {/* QUICK START TEMPLATES */}
      <section style={{ marginTop: 56 }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 20 }}>
          <h2 className="section-title">Quick start templates</h2>
          <button className="btn btn-sm btn-ghost" onClick={() => onNavigate("/templates")}>
            All templates <Icons.ArrowRight size={13} />
          </button>
        </div>
        {!templates ? (
          <div className="grid-3">
            {[0, 1, 2].map((i) => (
              <div key={i} className="skeleton-bar" style={{ height: 220, borderRadius: 14 }}></div>
            ))}
          </div>
        ) : (
          <>
            <div className="grid-3">
              {templates.slice(0, 3).map((t) => <TemplateCard key={t.id} template={t} onClick={() => onOpenTemplate(t)} />)}
            </div>
            {templates.length > 3 && (
              <div className="grid-2" style={{ marginTop: 16 }}>
                {templates.slice(3, 5).map((t) => <TemplateCard key={t.id} template={t} onClick={() => onOpenTemplate(t)} variant="wide" />)}
              </div>
            )}
          </>
        )}
      </section>

      {/* AI GENERATE BLOCK + BRAND PREVIEW */}
      <section style={{ marginTop: 56, display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 20 }}>
        <div
          className="card hover-card promo-invert"
          style={{
            color: "white",
            padding: 36,
            display: "flex",
            flexDirection: "column",
            justifyContent: "space-between",
            minHeight: 320,
            position: "relative",
            overflow: "hidden",
          }}
          onClick={() => onNavigate("/generate")}
        >
          <div>
            <div className="eyebrow" style={{ color: "#FFFFFF" }}>GENERATE FROM SCRATCH</div>
            <h3 style={{ fontFamily: "var(--font-display)", fontSize: 56, fontWeight: 700, letterSpacing: "-0.035em", lineHeight: 0.98, margin: "12px 0 0", maxWidth: 520 }}>
              Notion in.<br />
              Carousel out.
            </h3>
            <p style={{ color: "#A7A6A6", fontSize: 16, lineHeight: 1.45, marginTop: 16, maxWidth: 460 }}>
              Paste a brief, link a Notion doc, or describe the idea. AI generates a fully editable carousel in your brand.
            </p>
          </div>
          <div style={{ display: "flex", gap: 12, marginTop: 24 }}>
            <div className="btn btn-yellow">
              <Icons.Wand size={14} /> Start with AI
            </div>
            <div style={{ color: "#8E8E8E", fontSize: 12, alignSelf: "center" }}>
              Notion · URL · Text · Upload
            </div>
          </div>
        </div>

        <div
          className="card hover-card"
          style={{ padding: 28, background: "var(--surface)", borderColor: "var(--line)" }}
          onClick={() => onNavigate("/brand")}
        >
          <div className="eyebrow">BRAND FOUNDATIONS</div>
          <h3 style={{ fontFamily: "var(--font-display)", fontSize: 32, fontWeight: 700, letterSpacing: "-0.035em", margin: "10px 0 16px" }}>
            Your kit of decisions.
          </h3>
          {/* color swatches */}
          <div style={{ display: "flex", gap: 6, marginBottom: 16 }}>
            {["#070707", "#1A1A1A", "#383838", "#E9E9F0", "#6E6E6E", "#FFFFFF"].map((c) => (
              <div key={c} title={c} style={{ width: 32, height: 32, borderRadius: 8, background: c, border: "1px solid var(--line)" }} />
            ))}
            {/* Holographic foil — the brand's expressive finish, not a flat color */}
            <div
              title="Holographic foil"
              style={{
                width: 32, height: 32, borderRadius: 8, border: "1px solid var(--line)",
                backgroundImage:
                  "url(assets/holo-texture.png), conic-gradient(from 210deg, #ff9ce3, #a0e9ff, #b9ffce, #fff6a0, #ffb3d1, #c9a0ff, #ff9ce3)",
                backgroundSize: "cover, cover",
                backgroundBlendMode: "overlay",
                boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.35)",
              }}
            />
          </div>
          {/* type sample */}
          <div style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 700, letterSpacing: "-0.025em" }}>
            Rebond Grotesque · Aspekta
          </div>
          <div style={{ marginTop: 18, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <div style={{ fontSize: 12, color: "var(--ink-3)" }}>Colors · Type · Voice · Imagery</div>
            <Icons.ArrowRight size={16} />
          </div>
        </div>
      </section>

      {/* WHAT YOU CAN DO */}
      <section style={{ marginTop: 56 }}>
        <h2 className="section-title">What you can do here</h2>
        <div className="grid-4" style={{ marginTop: 20 }}>
          {[
            { icon: "Grid", title: "Templates", body: "Four ready formats — LinkedIn carousel, Spotify, Instagram, and YouTube." },
            { icon: "Wand", title: "Generate", body: "Turn briefs, links, and notes into branded assets." },
            { icon: "Palette", title: "Brand Foundations", body: "Colors, type, voice — exported as MD or styled in-tool." },
            { icon: "Download", title: "Export anywhere", body: "PNG, PDF, or copy as code — same kit, every channel." },
          ].map((f) => {
            const I = Icons[f.icon];
            return (
              <div key={f.title} className="card" style={{ padding: 20 }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: "var(--bg)", display: "grid", placeItems: "center", marginBottom: 14 }}>
                  <I size={18} />
                </div>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 17, fontWeight: 600, letterSpacing: "-0.01em" }}>{f.title}</div>
                <p style={{ fontSize: 13, color: "var(--ink-3)", lineHeight: 1.5, margin: "6px 0 0" }}>{f.body}</p>
              </div>
            );
          })}
        </div>
      </section>

      {/* RECENT */}
      <section style={{ marginTop: 56 }}>
        <h2 className="section-title">Recently edited</h2>
        <div style={{ marginTop: 16, padding: 28, border: "1px dashed var(--line-2)", borderRadius: 20, textAlign: "center", background: "var(--surface)" }}>
          <p style={{ color: "var(--ink-3)", fontSize: 14, margin: 0 }}>
            Nothing here yet. Open a template to start editing.
          </p>
        </div>
      </section>
    </div>
  );
}

// =================================================================
// Template card — used on home + templates page
// =================================================================
function TemplateCard({ template, onClick, variant = "default" }) {
  const slide = template.slides[0];
  return (
    <div className="card hover-card" style={{ padding: 14 }} onClick={onClick}>
      <TemplateThumbnail template={template} />
      <div style={{ padding: "14px 6px 4px", display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 12 }}>
        <div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 600, letterSpacing: "-0.015em" }}>{template.name}</div>
          <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{template.platform}</div>
        </div>
        <div className="pill">{template.width}×{template.height}</div>
      </div>
    </div>
  );
}

// Render a template thumbnail at a fixed display width
function TemplateThumbnail({ template, displayWidth }) {
  const wrapRef = useRef(null);
  const [width, setWidth] = useState(displayWidth || 280);
  useEffect(() => {
    if (displayWidth) return;
    const update = () => {
      if (wrapRef.current) setWidth(wrapRef.current.clientWidth);
    };
    update();
    const ro = new ResizeObserver(update);
    if (wrapRef.current) ro.observe(wrapRef.current);
    return () => ro.disconnect();
  }, [displayWidth]);
  const scale = width / template.width;
  const height = template.height * scale;
  return (
    <div
      ref={wrapRef}
      style={{
        width: "100%",
        height,
        borderRadius: 12,
        overflow: "hidden",
        background: template.slides[0].background,
        position: "relative",
      }}
    >
      {template.preview ? (
        <img
          src={template.preview}
          alt={template.name}
          style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", display: "block" }}
        />
      ) : (
        <SlideRenderer slide={template.slides[0]} width={template.width} height={template.height} scale={scale} />
      )}
    </div>
  );
}

window.HomePage = HomePage;
window.TemplateCard = TemplateCard;
window.TemplateThumbnail = TemplateThumbnail;
