// VELOUR marketing site — four live pillar demos. Each section pairs editorial copy
// with a working miniature of the product: check a ritual and the ring closes,
// wear a piece and its cost-per-wear falls. Demo data only — nothing persists.
const { Card } = window.VelourDesignSystem_380ed4;

// Runs the enter animation once, when the element scrolls into view.
function useInView(threshold = 0.35) {
  const ref = React.useRef(null);
  const [inView, setInView] = React.useState(false);
  React.useEffect(() => {
    if (!("IntersectionObserver" in window)) { setInView(true); return; }
    const io = new IntersectionObserver((es) => {
      es.forEach((e) => { if (e.isIntersecting) { setInView(true); io.disconnect(); } });
    }, { threshold });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return [ref, inView];
}

const demoEase = "cubic-bezier(.16,1,.3,1)";

// Shared frame for each demo's product card.
function DemoCard({ label, greet, date, children }) {
  return (
    <div aria-label={label} style={{ background: "var(--surface-card)", border: "var(--border-width) solid var(--border)", borderRadius: 22, padding: "30px 28px", boxShadow: "0 30px 60px -40px rgba(44,44,42,.35)" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 24 }}>
        <span style={{ fontFamily: "var(--font-serif)", fontSize: 19, color: "var(--text-primary)" }}>{greet}</span>
        <span style={{ fontSize: 12, color: "var(--text-tertiary)", letterSpacing: "0.08em", textTransform: "uppercase" }}>{date}</span>
      </div>
      {children}
    </div>
  );
}

// Copy column + card, alternating sides.
function DemoRow({ id, flip, accent, eyebrow, title, lede, points, card }) {
  const copy = (
    <div key="copy" className="vlr-demo-copy">
      <window.Eyebrow color={accent} style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <i aria-hidden="true" style={{ width: 8, height: 8, borderRadius: "50%", background: accent, display: "inline-block" }}></i>
        {eyebrow}
      </window.Eyebrow>
      <h2 style={{ fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: 40, lineHeight: 1.12, letterSpacing: "-0.02em", color: "var(--text-primary)", margin: "18px 0 0", textWrap: "balance" }}>{title}</h2>
      <p style={{ fontSize: 17, lineHeight: 1.7, color: "var(--text-secondary)", maxWidth: 440, margin: "20px 0 0" }}>{lede}</p>
      <ul style={{ listStyle: "none", padding: 0, margin: "26px 0 0", display: "flex", flexDirection: "column", gap: 12 }}>
        {points.map((pt) => (
          <li key={pt} style={{ display: "flex", alignItems: "flex-start", gap: 14, fontSize: 15, color: "var(--text-primary)" }}>
            <span aria-hidden="true" style={{ width: 8, height: 1.5, background: "var(--text-tertiary)", marginTop: 11, flexShrink: 0 }}></span>
            <span style={{ lineHeight: 1.55 }}>{pt}</span>
          </li>
        ))}
      </ul>
    </div>
  );
  const visual = <div key="visual" className="vlr-demo-visual">{card}</div>;
  return (
    <div id={id} className="vlr-demo-row">
      {flip ? [visual, copy] : [copy, visual]}
    </div>
  );
}

/* ---------- Rituals: check in, the ring closes ---------- */
const RING_CIRC = 465; /* 2πr for r=74 */
const RITUAL_ITEMS = ["Morning pages, 10 minutes", "Stretch before coffee", "Phone stays outside the bedroom"];
const RITUAL_LINES = [
  "One kept. The day is underway.",
  "Two of three. Almost a full morning.",
  "All three. Day 15 of the hold begins tomorrow.",
];

function RitualsDemo() {
  const [ref, inView] = useInView();
  const [done, setDone] = React.useState([false, false, false]);
  const kept = done.filter(Boolean).length;
  const days = kept === 3 ? 15 : 14;
  const pct = inView ? Math.min(days / 21, 1) : 0; /* 21-day ring cycle */
  const toggle = (i) => setDone((d) => d.map((v, j) => (j === i ? !v : v)));
  return (
    <DemoCard label="Rituals demo" greet="This morning" date="Today">
      <div ref={ref} style={{ display: "flex", gap: 30, alignItems: "center", flexWrap: "wrap" }}>
        <div style={{ position: "relative", width: 168, height: 168, flex: "none" }}>
          <svg width="168" height="168" viewBox="0 0 168 168" role="img" aria-label="Hold ring" style={{ transform: "rotate(-90deg)" }}>
            <circle cx="84" cy="84" r="74" fill="none" strokeWidth="9" stroke="var(--border)" opacity="0.6" />
            <circle cx="84" cy="84" r="74" fill="none" strokeWidth="9" stroke="var(--sage)" strokeLinecap="round"
              strokeDasharray={RING_CIRC} strokeDashoffset={RING_CIRC - RING_CIRC * pct}
              style={{ transition: `stroke-dashoffset 1.4s ${demoEase}` }} />
          </svg>
          <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
            <b style={{ fontFamily: "var(--font-serif)", fontSize: 44, fontWeight: 500, lineHeight: 1, color: "var(--text-primary)" }}>{days}</b>
            <span style={{ fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--text-tertiary)", marginTop: 6 }}>day hold</span>
          </div>
        </div>
        <div style={{ flex: 1, minWidth: 200, display: "grid", gap: 10 }}>
          {RITUAL_ITEMS.map((name, i) => {
            const d = done[i];
            return (
              <button key={name} onClick={() => toggle(i)} aria-pressed={d} style={{
                display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", width: "100%", textAlign: "left",
                border: `1px solid ${d ? "color-mix(in srgb, var(--sage) 40%, var(--border))" : "var(--border)"}`,
                borderRadius: 12, fontSize: 14, fontFamily: "var(--font-sans)", cursor: "pointer",
                background: d ? "color-mix(in srgb, var(--sage) 7%, transparent)" : "transparent",
                color: d ? "var(--text-tertiary)" : "var(--text-primary)",
                transition: `background .35s ${demoEase}, border-color .35s ${demoEase}, color .35s ${demoEase}`,
              }}>
                <span style={{ width: 20, height: 20, borderRadius: "50%", flex: "none", display: "grid", placeItems: "center", border: `1.5px solid ${d ? "var(--sage)" : "var(--border)"}`, background: d ? "var(--sage)" : "transparent", transition: "background .35s, border-color .35s" }}>
                  <svg width="11" height="9" viewBox="0 0 11 9" fill="none" style={{ opacity: d ? 1 : 0, transform: d ? "scale(1)" : "scale(.4)", transition: `.35s ${demoEase}` }}>
                    <path d="M1 4.5L4 7.5L10 1" stroke="#F7F4EF" strokeWidth="1.8" strokeLinecap="round" />
                  </svg>
                </span>
                <span>{name}</span>
              </button>
            );
          })}
        </div>
      </div>
      <p style={{ marginTop: 18, minHeight: "1.5em", fontSize: 13.5, color: "var(--sage)", fontFamily: "var(--font-serif)", fontStyle: "italic" }}>
        {kept === 0 ? "Tap a ritual to check in." : RITUAL_LINES[kept - 1]}
      </p>
    </DemoCard>
  );
}

/* ---------- Wellness: gauges fill, the score counts ---------- */
const GAUGE_CIRC = 226; /* 2πr for r=36 */
const GAUGES = [
  { pct: 88, val: "7.4h", label: "Sleep" },
  { pct: 72, val: "1.8L", label: "Hydration" },
  { pct: 81, val: "8.1k", label: "Steps" },
];

function WellnessDemo() {
  const [ref, inView] = useInView();
  const [score, setScore] = React.useState(0);
  React.useEffect(() => {
    if (!inView) return;
    const reduced = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const target = 81, dur = reduced ? 1 : 1500, t0 = performance.now();
    let raf;
    const tick = (t) => {
      const k = Math.min((t - t0) / dur, 1);
      setScore(Math.round(target * (1 - Math.pow(1 - k, 3))));
      if (k < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [inView]);
  return (
    <DemoCard label="Wellness demo" greet="This week" date="Mon – Sun">
      <div ref={ref} style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14, marginBottom: 26 }}>
        {GAUGES.map((g) => (
          <div key={g.label} style={{ textAlign: "center" }}>
            <div style={{ position: "relative", width: 86, height: 86, margin: "0 auto" }}>
              <svg width="86" height="86" viewBox="0 0 86 86" style={{ transform: "rotate(-90deg)" }}>
                <circle cx="43" cy="43" r="36" fill="none" strokeWidth="7" stroke="var(--border)" opacity="0.55" />
                <circle cx="43" cy="43" r="36" fill="none" strokeWidth="7" stroke="var(--teal)" strokeLinecap="round"
                  strokeDasharray={GAUGE_CIRC} strokeDashoffset={inView ? GAUGE_CIRC - (GAUGE_CIRC * g.pct) / 100 : GAUGE_CIRC}
                  style={{ transition: `stroke-dashoffset 1.5s ${demoEase}` }} />
              </svg>
              <span style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", fontWeight: 600, fontSize: 15, color: "var(--text-primary)" }}>{g.val}</span>
            </div>
            <label style={{ display: "block", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--text-tertiary)", marginTop: 10 }}>{g.label}</label>
          </div>
        ))}
      </div>
      <div style={{ borderTop: "1px solid var(--border)", paddingTop: 22, display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
        <div>
          <span style={{ display: "block", fontSize: 12, color: "var(--text-tertiary)", letterSpacing: "0.14em", textTransform: "uppercase" }}>Wellness score</span>
          <b style={{ fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: 52, lineHeight: 1.15, color: "var(--text-primary)" }}>{score}</b>
        </div>
        <span style={{ fontSize: 13, color: "var(--teal)", fontWeight: 500 }}>+6 from last week</span>
      </div>
    </DemoCard>
  );
}

/* ---------- Wardrobe: wear a piece, cost-per-wear recalculates ---------- */
const CAPSULE_START = [
  { name: "Beige coat", swatch: "#C8BFAE", price: 240, worn: 61 },
  { name: "Navy knit", swatch: "#3E4A52", price: 88, worn: 34 },
  { name: "Wool trouser", swatch: "#7A6E5D", price: 165, worn: 12 },
  { name: "White oxford", swatch: "#EDE7DB", price: 120, worn: 48 },
  { name: "Suede loafer", swatch: "#5A5348", price: 210, worn: 8 },
  { name: "Linen shirt", swatch: "#9C8F7A", price: 95, worn: 27 },
];

function WardrobeDemo() {
  const [pieces, setPieces] = React.useState(CAPSULE_START.map((p) => ({ ...p, wornToday: false })));
  const wear = (i) => setPieces((ps) => ps.map((p, j) => (j === i ? { ...p, worn: p.worn + 1, wornToday: true } : p)));
  const avg = pieces.reduce((s, p) => s + p.price / p.worn, 0) / pieces.length;
  return (
    <DemoCard label="Wardrobe demo" greet="Your capsule" date={`${pieces.length} pieces`}>
      <style>{`
        .vlw-piece { transition: border-color .35s ${demoEase}, transform .35s ${demoEase}; }
        /* See the note in DashWardrobe: a hover-revealed affordance costs a tap on
           touch. The tag is the whole invitation here — "Tap a piece to wear it
           today" — so on a phone it is simply visible. */
        .vlw-tag { opacity: 0; transform: scale(.7); transition: .35s ${demoEase}; }
        .vlw-tag.vlw-worn { opacity: 1; transform: none; }
        @media (hover: hover) and (pointer: fine) {
          .vlw-piece:hover { border-color: var(--amber) !important; transform: translateY(-3px); }
          .vlw-piece:hover .vlw-tag { opacity: 1; transform: none; }
        }
        @media (hover: none) { .vlw-tag { opacity: 1; transform: none; } }
        @media (prefers-reduced-motion: reduce) { .vlw-piece, .vlw-tag { transition: none; } }
      `}</style>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
        {pieces.map((p, i) => (
          <button key={p.name} className="vlw-piece" onClick={() => wear(i)} style={{
            position: "relative", border: "1px solid var(--border)", borderRadius: 14, padding: "16px 14px",
            display: "flex", flexDirection: "column", gap: 8, textAlign: "left", width: "100%",
            background: "transparent", cursor: "pointer", fontFamily: "var(--font-sans)",
          }}>
            <span className={"vlw-tag" + (p.wornToday ? " vlw-worn" : "")} style={{ position: "absolute", top: 8, right: 8, fontSize: 10, letterSpacing: "0.08em", background: "var(--amber)", color: "#fff", borderRadius: 999, padding: "3px 8px" }}>{p.wornToday ? "Worn today" : "Wear today"}</span>
            <span style={{ width: "100%", height: 44, borderRadius: 8, background: p.swatch, display: "block", marginBottom: 2 }}></span>
            <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-primary)" }}>{p.name}</span>
            <span style={{ fontSize: 12, color: "var(--text-tertiary)" }}><b style={{ color: "var(--amber-text)", fontWeight: 600 }}>${(p.price / p.worn).toFixed(2)}</b> / wear · worn {p.worn}×</span>
          </button>
        ))}
      </div>
      <div style={{ marginTop: 20, borderTop: "1px solid var(--border)", paddingTop: 16, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
        <span style={{ fontSize: 14, color: "var(--text-secondary)" }}>Capsule average</span>
        <div style={{ textAlign: "right" }}>
          <b style={{ fontFamily: "var(--font-serif)", fontSize: 30, fontWeight: 500, color: "var(--text-primary)" }}>${avg.toFixed(2)}</b>
          <div style={{ fontSize: 11, color: "var(--text-tertiary)", letterSpacing: "0.12em", textTransform: "uppercase" }}>per wear</div>
        </div>
      </div>
    </DemoCard>
  );
}

/* ---------- Efficiency: ROI tiers + weekly return bars ---------- */
const ROI_TASKS = {
  high: [["Grocery order before the fridge empties", "Do first"], ["Prep tomorrow's client call", "Do first"], ["Sunday meal prep — four dinners", "Do first"]],
  medium: [["Batch errands into one trip", "Batch together"], ["Answer the week's email", "Batch together"], ["Schedule dentist and oil change", "Batch together"]],
  low: [["Reorganize the pantry", "Defer or delete"], ["Compare three note apps", "Defer or delete"], ["Rewatch the settings tutorial", "Defer or delete"]],
};
// Weekends carry real bars — errands and meal prep count as much as a work Tuesday.
const WEEK_BARS = [
  { d: "M", h: 52 }, { d: "T", h: 74 }, { d: "W", h: 66 }, { d: "T", h: 92 }, { d: "F", h: 80 },
  { d: "S", h: 44 }, { d: "S", h: 86 },
];

function EfficiencyDemo() {
  const [ref, inView] = useInView();
  const [tier, setTier] = React.useState("high");
  return (
    <DemoCard label="Efficiency demo" greet="This week's ledger" date="Returned: 6.5h · $49">
      <style>{`
        @keyframes vleTaskIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
        @media (prefers-reduced-motion: reduce) { .vle-task { animation: none !important; } }
      `}</style>
      <div role="tablist" aria-label="ROI tiers" style={{ display: "flex", gap: 8, marginBottom: 22 }}>
        {[["high", "High ROI"], ["medium", "Medium ROI"], ["low", "Low ROI"]].map(([key, label]) => {
          const active = tier === key;
          return (
            <button key={key} role="tab" aria-selected={active} onClick={() => setTier(key)} style={{
              padding: "8px 16px", borderRadius: 999, fontSize: 12, letterSpacing: "0.06em", cursor: "pointer", fontFamily: "var(--font-sans)",
              border: `1px solid ${active ? "var(--terracotta)" : "var(--border)"}`,
              background: active ? "var(--terracotta)" : "transparent", color: active ? "#fff" : "var(--text-secondary)",
              transition: `.3s ${demoEase}`,
            }}>{label}</button>
          );
        })}
      </div>
      <div role="tabpanel" style={{ display: "grid", gap: 10, minHeight: 170 }}>
        {ROI_TASKS[tier].map(([name, roi], i) => (
          <div key={name} className="vle-task" style={{
            display: "flex", justifyContent: "space-between", alignItems: "center",
            border: "1px solid var(--border)", borderRadius: 12, padding: "13px 16px", fontSize: 14, color: "var(--text-primary)",
            animation: `vleTaskIn .5s ${demoEase} both`, animationDelay: `${i * 0.08}s`,
          }}>
            <span>{name}</span>
            <span style={{ fontSize: 11.5, color: "var(--terracotta)", fontWeight: 600, letterSpacing: "0.06em" }}>{roi}</span>
          </div>
        ))}
      </div>
      <div ref={ref} aria-label="Tasks resolved by day" style={{ display: "flex", gap: 10, alignItems: "flex-end", height: 110, marginTop: 26, borderTop: "1px solid var(--border)", paddingTop: 20 }}>
        {WEEK_BARS.map((b, i) => (
          <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 8, height: "100%", justifyContent: "flex-end" }}>
            <i style={{
              width: "100%", maxWidth: 34, height: `${b.h}%`, borderRadius: "6px 6px 2px 2px", display: "block",
              background: b.dim ? "var(--border)" : "var(--terracotta)",
              transform: inView ? "scaleY(1)" : "scaleY(0)", transformOrigin: "bottom",
              transition: `transform 1.1s ${demoEase} ${i * 0.05}s`,
            }}></i>
            <label style={{ fontSize: 10.5, color: "var(--text-tertiary)", letterSpacing: "0.1em" }}>{b.d}</label>
          </div>
        ))}
      </div>
    </DemoCard>
  );
}

/* ---------- assembly ---------- */
function FeatureSplit() {
  return (
    <window.Section pad={112} style={{ display: "flex", flexDirection: "column", gap: 112 }}>
      <style>{`
        .vlr-demo-row { display: grid; grid-template-columns: 1fr 1fr; gap: 72px; align-items: center; scroll-margin-top: 88px; }
        /* Two columns need 554px and never had a breakpoint, which is what scrolled
           the whole marketing page sideways on a phone. Stacked, the copy always
           leads — a demo card above its own explanation reads as an orphan. */
        @media (max-width: 900px) {
          .vlr-demo-row { grid-template-columns: 1fr; gap: 34px; }
          .vlr-demo-copy { order: 1; }
          .vlr-demo-visual { order: 2; }
        }
      `}</style>
      <DemoRow
        id="demo-rituals"
        accent="var(--sage)"
        eyebrow="Pillar one — Rituals"
        title="Small acts, kept daily, become architecture."
        lede="VELOUR treats a habit as a ritual — something you return to, not something you owe. Check in each morning and evening. Watch the ring close."
        points={[
          "Ritual builder for morning and evening sequences",
          "Holds framed as compounding, never as pressure",
          "A weekly reflection, written from your own data",
        ]}
        card={<RitualsDemo />}
      />
      <DemoRow
        id="demo-wellness"
        flip
        accent="var(--teal)"
        eyebrow="Pillar two — Wellness"
        title="One number that tells the truth about your week."
        lede="Sleep, hydration, movement, and mindfulness — measured quietly, composed into a single weekly score with the breakdown right beneath it."
        points={[
          "Ring gauges for sleep, hydration, and steps",
          "A sleep timeline that shows patterns, not judgments",
          "A weekly score from 0 to 100, explained in plain terms",
        ]}
        card={<WellnessDemo />}
      />
      <DemoRow
        id="demo-wardrobe"
        accent="var(--amber)"
        eyebrow="Pillar three — Wardrobe"
        title="Your capsule, priced by the wear."
        lede="Every piece earns its place. VELOUR divides what you paid by how often you reach for it — and tells you, kindly, what you already know. Tap a piece to wear it today."
        points={[
          "Capsule grid with cost-per-wear on every piece",
          "A weekly outfit planner built from what you own",
          "Quiet notes on what hasn't left the hanger",
        ]}
        card={<WardrobeDemo />}
      />
      <DemoRow
        id="demo-efficiency"
        flip
        accent="var(--terracotta)"
        eyebrow="Pillar four — Efficiency"
        title="Time, sorted by what it returns."
        lede="Every task lands in one of three tiers. High ROI, do first. Medium ROI, batch together. Low ROI, defer — or delete without guilt."
        points={[
          "Time reclaimed and money kept, in honest weekly numbers",
          "Spending by category, without the shame graph",
          "Task batching by ROI tier, not priority numbers",
        ]}
        card={<EfficiencyDemo />}
      />
    </window.Section>
  );
}

window.FeatureSplit = FeatureSplit;
