/* Lesson 01 — Guided 5-step studio.
   She answers 5 questions, watches a live preview update,
   then hits "Ship it" to apply changes. */

function Lesson01Studio({ onComplete, onBack }) {
  const [step, setStep] = React.useState(() => {
    try {
      const saved = JSON.parse(localStorage.getItem("delaney.lesson.01.studio") || "{}");
      return saved.step || 0;
    } catch { return 0; }
  });

  const [answers, setAnswers] = React.useState(() => {
    try {
      const saved = JSON.parse(localStorage.getItem("delaney.lesson.01.studio") || "{}");
      return saved.answers || {
        storeType: "",
        vibe: "",
        products: "",
        mattersToYou: "",
        tagline: "",
      };
    } catch {
      return { storeType: "", vibe: "", products: "", mattersToYou: "", tagline: "" };
    }
  });

  const [shipped, setShipped] = React.useState(() => !!localStorage.getItem("delaney.lesson.01.shipped"));

  React.useEffect(() => {
    try { localStorage.setItem("delaney.lesson.01.studio", JSON.stringify({ step, answers })); } catch {}
  }, [step, answers]);

  const STEPS = [
    {
      key: "storeType",
      icon: "🏪",
      title: "What kind of store is laneymae.com?",
      hint: "Clothing? Candy? Makeup? Music? Honestly anything. Picking one is the only hard part.",
      placeholder: "Clothing store, candy store, makeup, music project...",
      examples: ["Clothing store", "Candy store", "Makeup", "Music shop", "Photo prints"],
    },
    {
      key: "vibe",
      icon: "🎨",
      title: "What's the vibe?",
      hint: "Pick a word. Soft / sharp / weird / cozy / loud / cool. Your color palette comes from this.",
      placeholder: "Soft, sharp, weird, cozy, loud, cool...",
      examples: ["soft & dreamy", "sharp & minimal", "loud & bright", "cozy & warm", "weird & cool"],
    },
    {
      key: "products",
      icon: "🛍️",
      title: "What 3 things do you actually want to sell?",
      hint: "Get specific. Not 'clothes' — name the actual thing. 'Vintage band tees,' 'glittery hair clips,' 'cherry chapstick.'",
      placeholder: "Three items, comma-separated...",
      examples: ["vintage band tees, denim shorts, sunflower earrings", "matte lipsticks, eyeshadow, glittery liners"],
    },
    {
      key: "mattersToYou",
      icon: "💭",
      title: "What actually matters to you about this?",
      hint: "Where the stuff comes from? That it's affordable? That it feels handmade? That it pisses off your parents? Whatever — be real.",
      placeholder: "What's the point of this store, for you?",
      examples: ["everything is secondhand", "affordable for college kids", "looks expensive but isn't", "handmade by people you can google"],
    },
    {
      key: "tagline",
      icon: "✨",
      title: "One line. Tag the store.",
      hint: "5-8 words. Don't overthink. 'Vintage clothes for girls with taste.' Or 'Candy your dentist would hate.'",
      placeholder: "Tag the store in 5-8 words...",
      examples: ["Vintage clothes for girls with taste", "Candy your dentist would hate"],
    },
  ];

  const currentStep = STEPS[step];
  const allDone = step >= STEPS.length;
  const progressPct = allDone ? 100 : (step / STEPS.length) * 100;

  function updateAnswer(value) {
    setAnswers({ ...answers, [currentStep.key]: value });
  }

  function next() {
    if (step < STEPS.length) setStep(step + 1);
  }

  function back() {
    if (step > 0) setStep(step - 1);
  }

  function shipIt() {
    // Save final config + mark shipped
    localStorage.setItem("delaney.lesson.01.studio.final", JSON.stringify(answers));
    localStorage.setItem("delaney.lesson.01.shipped", new Date().toISOString());
    setShipped(true);
  }

  function markComplete() {
    localStorage.setItem("delaney.lesson.01.complete", new Date().toISOString());
    alert("🎉 Lesson 01 complete. $15 added to your cash-out. Go check your dashboard.");
    if (onComplete) onComplete();
  }

  // PREVIEW palette based on vibe
  const vibePalettes = {
    soft: { bg: "#FCEEF0", accent: "#E89AB0", text: "#3A2538" },
    "soft & dreamy": { bg: "#FCEEF0", accent: "#E89AB0", text: "#3A2538" },
    sharp: { bg: "#F4F4F0", accent: "#1A1A1A", text: "#1A1A1A" },
    "sharp & minimal": { bg: "#F4F4F0", accent: "#1A1A1A", text: "#1A1A1A" },
    loud: { bg: "#FFEC4A", accent: "#FF3D7F", text: "#1A1A1A" },
    "loud & bright": { bg: "#FFEC4A", accent: "#FF3D7F", text: "#1A1A1A" },
    cozy: { bg: "#F4ECDC", accent: "#A06544", text: "#3A2812" },
    "cozy & warm": { bg: "#F4ECDC", accent: "#A06544", text: "#3A2812" },
    weird: { bg: "#1E1B3A", accent: "#9BFF00", text: "#FFE9C9" },
    "weird & cool": { bg: "#1E1B3A", accent: "#9BFF00", text: "#FFE9C9" },
    cool: { bg: "#E8F0F2", accent: "#3F6377", text: "#0F2231" },
  };
  const vibeKey = (answers.vibe || "soft").toLowerCase().split(",")[0].trim();
  const palette = vibePalettes[vibeKey] || vibePalettes.soft;

  return (
    <main className="page-enter" data-screen-label="Lesson 01 Studio">
      <section className="studio-page">
        <div className="shell">
          <button className="link-underline" onClick={onBack} style={{ marginBottom: 24 }}>
            <span aria-hidden="true">←</span> Back to lesson
          </button>

          {/* Step progress bar */}
          <div className="studio-progress">
            <div className="studio-progress-bar">
              <div className="studio-progress-fill" style={{ width: progressPct + "%" }}></div>
            </div>
            <div className="studio-progress-label">
              {allDone ? "All 5 done · Ready to ship" : `Step ${step + 1} of ${STEPS.length}`}
            </div>
          </div>

          <div className="studio-grid">
            {/* LEFT: Question / form */}
            <div className="studio-question">
              {allDone ? (
                <div>
                  <div className="eyebrow" style={{ color: "var(--sage-deep)" }}>✓ Five answers in</div>
                  <h2 className="serif" style={{ fontSize: "clamp(32px, 4.5vw, 52px)", lineHeight: 1.1, fontWeight: 500, margin: "16px 0 24px" }}>
                    Take a look. Like it?
                  </h2>
                  <p className="welcome-lead">
                    That's <strong>{answers.storeType || "your store"}</strong> with a{" "}
                    <strong>{answers.vibe || "your"}</strong> vibe.
                    {answers.tagline && <> Tagline: "<em>{answers.tagline}</em>"</>}
                  </p>
                  <p className="welcome-lead pitch-lead--muted" style={{ fontSize: 16 }}>
                    {shipped ? "✅ Shipped. Your version is saved." : "Hit Ship It to lock this in. You can keep playing afterward — change anything, add anything. The first version doesn't have to be the final version."}
                  </p>
                  <div style={{ display: "flex", gap: 14, marginTop: 28, flexWrap: "wrap" }}>
                    <button className="link-underline" onClick={() => setStep(0)}>
                      <span aria-hidden="true">←</span> Change something
                    </button>
                    {!shipped && (
                      <button className="btn btn--terracotta" onClick={shipIt} style={{ fontSize: 16 }}>
                        Ship it →
                      </button>
                    )}
                    {shipped && (
                      <button className="btn btn--terracotta" onClick={markComplete} style={{ fontSize: 16 }}>
                        Mark Lesson 01 Complete · +$15
                      </button>
                    )}
                  </div>
                </div>
              ) : (
                <div>
                  <div className="eyebrow">Q{step + 1} of {STEPS.length}</div>
                  <h2 className="serif studio-q-h">
                    <span className="studio-q-icon">{currentStep.icon}</span>
                    {currentStep.title}
                  </h2>
                  <p className="welcome-lead" style={{ fontSize: 17 }}>{currentStep.hint}</p>
                  <textarea
                    className="studio-input"
                    placeholder={currentStep.placeholder}
                    value={answers[currentStep.key]}
                    onChange={(e) => updateAnswer(e.target.value)}
                    rows={3}
                    autoFocus
                  />
                  <div className="studio-examples">
                    <span className="eyebrow">Or pick one:</span>
                    {currentStep.examples.map((ex) => (
                      <button key={ex} className="studio-example-chip" onClick={() => updateAnswer(ex)}>
                        {ex}
                      </button>
                    ))}
                  </div>
                  <div className="studio-actions">
                    {step > 0 && (
                      <button className="link-underline" onClick={back}>
                        <span aria-hidden="true">←</span> Back
                      </button>
                    )}
                    <button
                      className="btn btn--terracotta"
                      onClick={next}
                      disabled={!answers[currentStep.key].trim()}
                      style={{ marginLeft: "auto", fontSize: 16 }}
                    >
                      {step === STEPS.length - 1 ? "See the result →" : "Next →"}
                    </button>
                  </div>
                </div>
              )}
            </div>

            {/* RIGHT: Live preview */}
            <div className="studio-preview">
              <div className="studio-preview-frame">
                <div className="studio-preview-bar">
                  <span className="studio-preview-dot"></span>
                  <span className="studio-preview-dot"></span>
                  <span className="studio-preview-dot"></span>
                  <span className="studio-preview-url">laneymae.com</span>
                </div>
                <div
                  className="studio-preview-site"
                  style={{ background: palette.bg, color: palette.text }}
                >
                  <div className="preview-nav">
                    <span style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 14 }}>Laney Mae</span>
                    <span style={{ fontSize: 11, opacity: 0.6 }}>cart · 0</span>
                  </div>
                  <div className="preview-hero">
                    <h3 style={{
                      fontFamily: "var(--display)",
                      fontSize: 32, lineHeight: 1.05,
                      margin: "20px 0 12px",
                      letterSpacing: "-0.02em",
                      fontWeight: 500,
                    }}>
                      {answers.storeType || "Your store name"}
                    </h3>
                    <p style={{ fontSize: 13, lineHeight: 1.5, opacity: 0.8, marginBottom: 18 }}>
                      {answers.tagline || (answers.vibe ? answers.vibe + " for the right kind of person" : "your tagline goes here")}
                    </p>
                    <button style={{
                      background: palette.accent,
                      color: palette.bg,
                      border: 0,
                      padding: "10px 22px",
                      borderRadius: 999,
                      fontSize: 13,
                      fontWeight: 600,
                    }}>Shop now</button>
                  </div>
                  <div className="preview-products">
                    {(answers.products || "item 1, item 2, item 3").split(",").slice(0, 3).map((p, i) => (
                      <div key={i} className="preview-product" style={{ background: "rgba(0,0,0,0.04)" }}>
                        <div style={{ aspectRatio: "1 / 1", background: palette.accent, opacity: 0.3, borderRadius: 6 }}></div>
                        <div style={{ fontSize: 11, marginTop: 6, fontWeight: 500 }}>{p.trim() || "item " + (i + 1)}</div>
                        <div style={{ fontSize: 10, opacity: 0.6 }}>$24</div>
                      </div>
                    ))}
                  </div>
                  {answers.mattersToYou && (
                    <div className="preview-mission">
                      <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.08em", opacity: 0.5, marginBottom: 4 }}>What we care about</div>
                      <div style={{ fontSize: 12, lineHeight: 1.5 }}>{answers.mattersToYou}</div>
                    </div>
                  )}
                </div>
              </div>
              <p style={{ fontSize: 13, color: "var(--ink-3)", textAlign: "center", marginTop: 12, fontStyle: "italic" }}>
                Updates live as you type ↑
              </p>
            </div>
          </div>
        </div>
      </section>

      <style>{`
        .studio-page { padding: clamp(32px, 5vw, 56px) 0 clamp(48px, 8vw, 96px); }
        .studio-progress { margin-bottom: 36px; max-width: 100%; }
        .studio-progress-bar {
          height: 6px; background: var(--cream-deep, #f3ece2); border-radius: 999px; overflow: hidden;
        }
        .studio-progress-fill {
          height: 100%; background: linear-gradient(90deg, var(--terracotta) 0%, var(--terracotta-deep) 100%);
          transition: width .4s cubic-bezier(.2, .8, .2, 1);
        }
        .studio-progress-label {
          font-family: var(--mono, monospace);
          font-size: 11px;
          letter-spacing: 0.08em;
          text-transform: uppercase;
          color: var(--ink-3);
          margin-top: 10px;
        }
        .studio-grid {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 48px;
          align-items: start;
        }
        @media (max-width: 900px) {
          .studio-grid { grid-template-columns: 1fr; gap: 32px; }
        }
        .studio-q-h {
          font-size: clamp(28px, 3.6vw, 42px);
          line-height: 1.15;
          margin: 16px 0 16px;
          font-weight: 500;
          display: flex;
          gap: 12px;
          align-items: center;
          flex-wrap: wrap;
        }
        .studio-q-icon { font-size: 36px; }
        .studio-input {
          width: 100%;
          padding: 16px 20px;
          font-size: 18px;
          font-family: var(--serif);
          background: var(--paper, #fff);
          border: 1px solid var(--line-strong);
          border-radius: 14px;
          outline: none;
          resize: vertical;
          min-height: 80px;
          margin-top: 20px;
          line-height: 1.4;
        }
        .studio-input:focus { border-color: var(--terracotta); }
        .studio-examples {
          margin-top: 18px;
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          align-items: center;
        }
        .studio-examples .eyebrow { margin-right: 8px; }
        .studio-example-chip {
          background: var(--cream-deep, #f3ece2);
          border: 1px solid var(--line);
          padding: 8px 14px;
          font-size: 13px;
          border-radius: 999px;
          cursor: pointer;
          font-family: var(--serif);
          color: var(--ink-1);
          transition: all .15s;
        }
        .studio-example-chip:hover {
          background: var(--terracotta-soft);
          border-color: var(--terracotta);
        }
        .studio-actions {
          display: flex; align-items: center;
          margin-top: 32px;
          gap: 16px;
        }

        /* PREVIEW */
        .studio-preview { position: sticky; top: 20px; }
        .studio-preview-frame {
          background: var(--paper, #fff);
          border-radius: 16px;
          overflow: hidden;
          box-shadow: 0 20px 50px rgba(0, 0, 0, 0.08);
          border: 1px solid var(--line);
        }
        .studio-preview-bar {
          display: flex;
          align-items: center;
          gap: 6px;
          padding: 12px 14px;
          background: var(--cream-deep, #f3ece2);
          border-bottom: 1px solid var(--line);
        }
        .studio-preview-dot {
          width: 10px; height: 10px; border-radius: 50%;
          background: var(--ink-3);
          opacity: 0.4;
        }
        .studio-preview-url {
          margin-left: 14px;
          font-family: var(--mono, monospace);
          font-size: 11px;
          color: var(--ink-3);
        }
        .studio-preview-site {
          padding: 24px 20px;
          min-height: 400px;
          transition: background .3s ease, color .3s ease;
        }
        .preview-nav {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding-bottom: 16px;
          border-bottom: 1px solid rgba(0,0,0,0.08);
        }
        .preview-hero { padding: 12px 0 24px; }
        .preview-products {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 10px;
          padding: 16px 0;
          border-top: 1px solid rgba(0,0,0,0.08);
        }
        .preview-product {
          padding: 8px;
          border-radius: 8px;
        }
        .preview-mission {
          margin-top: 18px;
          padding-top: 18px;
          border-top: 1px solid rgba(0,0,0,0.08);
        }
      `}</style>
    </main>
  );
}

window.Lesson01Studio = Lesson01Studio;
