/* Landing screen — three entry doors. */
/* global React, FRAMEWORK, sessionFromTemplate, sessionFromSample, emptySession */

function Landing({ project, setProject, setSession, setScreen, mode, setMode }) {
  const [door, setDoor] = useState(null); // 'blank' | 'template' | 'describe'
  const [pickedTemplate, setPickedTemplate] = useState(null);
  const [freeText, setFreeText] = useState("");
  const [llmThinking, setLlmThinking] = useState(false);
  const [llmReply, setLlmReply] = useState(null);

  const begin = (sessionLoader, projectName) => {
    if (projectName !== undefined) setProject(projectName);
    setSession(sessionLoader());
    setScreen("workspace");
  };

  // Quick start the canonical example
  const useExample = () => {
    setProject(FRAMEWORK.sample.project);
    setSession(sessionFromSample());
    setScreen("workspace");
  };

  const onPickTemplate = (t) => {
    setPickedTemplate(t);
  };

  const onConfirmTemplate = () => {
    if (!pickedTemplate) return;
    setProject(project || `Untitled — ${pickedTemplate.name.toLowerCase()}`);
    setSession(sessionFromTemplate(pickedTemplate.id));
    setScreen("workspace");
  };

  const onDescribe = async () => {
    if (!freeText.trim()) return;
    setLlmThinking(true);
    setLlmReply(null);
    // Simulated "LLM picks closest template" — keyword matching for the prototype
    await new Promise(r => setTimeout(r, 900));
    const text = freeText.toLowerCase();
    let bestId = "diagnostic";
    const score = (kw, w = 1) => text.includes(kw) ? w : 0;
    const scores = {
      diagnostic:        score("elisa") + score("diagnostic") + score("assay") + score("test kit") + score("lateral flow"),
      "binder-therapeutic": score("therapeutic") + score("antibody") + score("nanobody") + score("binder") + score("igg"),
      "industrial-enzyme":  score("enzyme") + score("lipase") + score("detergent") + score("industrial") + score("biocatal"),
      "vaccine-antigen":    score("vaccine") + score("antigen") + score("immun") + score("vlp"),
      "gene-therapy":       score("gene") + score("aav") + score("payload") + score("in vivo"),
      developability:       score("developability") + score("cmc") + score("late-stage"),
    };
    bestId = Object.entries(scores).sort((a, b) => b[1] - a[1])[0][0];
    const t = FRAMEWORK.templates.find(x => x.id === bestId);
    setLlmThinking(false);
    setLlmReply({
      template: t,
      clarifiers: [
        "Is this a single asset or a platform-wide effort?",
        "What’s the binding budget on thermostability — say-so or hard floor?",
      ],
    });
  };

  const onAcceptLLM = () => {
    if (!llmReply) return;
    setProject(project || freeText.split(/[.\n]/)[0].slice(0, 80));
    setSession(sessionFromTemplate(llmReply.template.id));
    setScreen("workspace");
  };

  return (
    <div style={{ maxWidth: 1200, margin: "0 auto", padding: "56px 32px 96px" }}>
      {/* Hero */}
      <header style={{ marginBottom: 56 }}>
        <div className="eyebrow violet" style={{ marginBottom: 18 }}>Protein Engineering</div>
        <h1 style={{
          fontFamily: "var(--font-jakarta)",
          fontSize: "clamp(2.4rem, 4.5vw, 4.2rem)",
          fontWeight: 800,
          lineHeight: 0.96,
          letterSpacing: "-0.025em",
          margin: 0,
          color: "var(--fg-1)",
          textWrap: "balance",
          maxWidth: 1000,
        }}>
          Quality Attributes
          <span style={{ fontFamily: "var(--font-jakarta)", fontWeight: 800, color: "var(--c-violet)" }}>.</span>
          <br />
          <span style={{ fontFamily: "var(--font-jakarta)", fontWeight: 400, color: "var(--fg-3)", fontSize: "0.55em", letterSpacing: "-0.015em" }}>
            For your protein. For this project. Today.
          </span>
        </h1>
        <p style={{
          maxWidth: 680,
          marginTop: 28,
          fontSize: 17,
          lineHeight: 1.65,
          color: "var(--fg-2)",
        }}>
          A framework of <strong style={{ color: "var(--fg-1)", fontWeight: 600 }}>10 groups</strong> and{" "}
          <strong style={{ color: "var(--fg-1)", fontWeight: 600 }}>56 leaf attributes</strong> covers every property a
          protein-engineering team might care about. Most of them don’t matter for your project — and that{" "}
          <em>is</em> the point. Pick the few that do; print the artifact; hang it on the wall.
        </p>
      </header>

      {/* Mode selector + project name */}
      <section style={{
        display: "grid",
        gridTemplateColumns: "1.4fr 1fr",
        gap: 24,
        marginBottom: 40,
      }}>
        {/* Project name */}
        <div className="card" style={{ padding: 28 }}>
          <div className="eyebrow" style={{ marginBottom: 14 }}>Project</div>
          <input
            className="cb-input"
            placeholder="What are we engineering?  e.g. Tool-grade nanobody for a flavivirus diagnostic ELISA"
            value={project}
            onChange={(e) => setProject(e.target.value)}
            style={{ fontSize: 18, padding: "14px 16px" }}
          />
          <div style={{ marginTop: 14, fontSize: 13, color: "var(--fg-4)" }}>
            The wall poster will be dated and labelled with this name. A new session next quarter produces a new poster — the drift is the message.
          </div>
        </div>

        {/* Mode toggle */}
        <div className="card" style={{ padding: 28 }}>
          <div className="eyebrow" style={{ marginBottom: 14 }}>Session mode</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
            {[
              { id: "self",     label: "Self-serve",  blurb: "5–15 min, one person, your laptop" },
              { id: "workshop", label: "Workshop",    blurb: "30–60 min, multi-person, projected" },
            ].map(m => (
              <button
                key={m.id}
                onClick={() => setMode(m.id)}
                style={{
                  appearance: "none",
                  textAlign: "left",
                  background: mode === m.id ? "var(--surface-navy)" : "transparent",
                  color: mode === m.id ? "var(--fg-on-dark)" : "var(--fg-1)",
                  border: `1px solid ${mode === m.id ? "var(--surface-navy)" : "var(--border-default)"}`,
                  borderRadius: "var(--radius-lg)",
                  padding: "14px 16px",
                  cursor: "pointer",
                  transition: "all 180ms var(--ease-out)",
                }}
              >
                <div style={{ fontFamily: "var(--font-jakarta)", fontWeight: 700, fontSize: 14 }}>{m.label}</div>
                <div style={{ fontSize: 12, marginTop: 4, opacity: 0.8, lineHeight: 1.45 }}>{m.blurb}</div>
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* Three doors */}
      <section style={{ marginBottom: 24 }}>
        <div className="eyebrow" style={{ marginBottom: 16, color: "var(--fg-4)" }}>Three ways in</div>
        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(3, 1fr)",
          gap: 18,
        }}>
          <DoorCard
            n="A"
            title="Start blank"
            blurb="Bias-free. The framework opens with everything unset. Best for facilitators who want the team to argue from zero."
            cta="Open empty framework"
            active={door === "blank"}
            onSelect={() => setDoor("blank")}
            onConfirm={() => begin(emptySession)}
          />
          <DoorCard
            n="B"
            title="Pick a template"
            blurb="Six common protein-engineering project shapes, each with a typical priority profile to refine."
            cta="Use this template"
            active={door === "template"}
            onSelect={() => setDoor("template")}
            onConfirm={onConfirmTemplate}
            confirmDisabled={!pickedTemplate}
          >
            <TemplateList picked={pickedTemplate} onPick={onPickTemplate} />
          </DoorCard>
          <DoorCard
            n="C"
            title="Describe in your words"
            blurb="Type a sentence about your project. Linus reads it, picks the closest template, asks a clarifying question."
            cta="Read my project"
            active={door === "describe"}
            onSelect={() => setDoor("describe")}
            onConfirm={onDescribe}
            confirmDisabled={!freeText.trim() || llmThinking}
          >
            <textarea
              className="cb-input"
              placeholder="e.g. We’re engineering a thermostable lipase for cold-water laundry detergent at 20 °C, single-shot dose, fed-batch process at 50 m³ scale."
              value={freeText}
              onChange={(e) => setFreeText(e.target.value)}
              rows={5}
              style={{ fontFamily: "var(--font-serif)", fontSize: 14, marginTop: 2 }}
            />
            {llmThinking && <LLMThinking />}
            {llmReply && <LLMReply reply={llmReply} onAccept={onAcceptLLM} />}
          </DoorCard>
        </div>
      </section>

      {/* Footer — example */}
      <div style={{
        marginTop: 56,
        padding: "22px 28px",
        borderTop: "1px solid var(--border-default)",
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        gap: 24,
        flexWrap: "wrap",
      }}>
        <div style={{ fontSize: 13, color: "var(--fg-3)", maxWidth: 640 }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-5)", marginRight: 12 }}>SEE IT IN MOTION</span>
          Load a worked example — a tool-grade nanobody for flavivirus ELISA — to see the workspace, pyramid and heatmap with realistic data.
        </div>
        <button className="btn btn-ghost" onClick={useExample}>
          Load nanobody example
          <span aria-hidden style={{ fontFamily: "var(--font-mono)", marginLeft: 4 }}>→</span>
        </button>
      </div>

      {/* Bottom site links */}
      <div style={{
        marginTop: 22,
        display: "flex",
        gap: 18,
        flexWrap: "wrap",
        fontFamily: "var(--font-mono)",
        fontSize: 11,
        letterSpacing: "0.08em",
        textTransform: "uppercase",
        color: "var(--fg-4)",
      }}>
        <a href="https://cranebioworks.com" target="_blank" rel="noopener noreferrer" style={{
          color: "var(--fg-3)", textDecoration: "none",
          borderBottom: "1px dotted rgba(34,49,83,0.2)", paddingBottom: 1,
        }}>cranebioworks.com →</a>
        <a href="mailto:hello@cranebioworks.com" style={{
          color: "var(--fg-3)", textDecoration: "none",
          borderBottom: "1px dotted rgba(34,49,83,0.2)", paddingBottom: 1,
        }}>hello@cranebioworks.com</a>
      </div>
    </div>
  );
}

function DoorCard({ n, title, blurb, cta, active, onSelect, onConfirm, confirmDisabled, children }) {
  return (
    <div
      onClick={() => !active && onSelect()}
      style={{
        background: active ? "rgba(255,255,255,0.9)" : "rgba(255,255,255,0.4)",
        border: `1px solid ${active ? "var(--c-violet)" : "var(--border-default)"}`,
        borderRadius: "var(--radius-xl)",
        padding: 24,
        cursor: active ? "default" : "pointer",
        transition: "all 200ms var(--ease-out)",
        boxShadow: active ? "0 20px 40px -16px rgba(104,90,217,0.20)" : "var(--shadow-card)",
        display: "flex",
        flexDirection: "column",
        minHeight: 200,
      }}
    >
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
        <span style={{
          width: 28, height: 28,
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          borderRadius: 8,
          background: active ? "var(--c-violet)" : "rgba(34,49,83,0.06)",
          color: active ? "#fff" : "var(--fg-3)",
          fontFamily: "var(--font-jakarta)", fontWeight: 700, fontSize: 13,
          transition: "all 180ms var(--ease-out)",
        }}>{n}</span>
        <h3 style={{
          fontFamily: "var(--font-jakarta)",
          fontSize: 19,
          fontWeight: 700,
          letterSpacing: "-0.01em",
          margin: 0,
        }}>{title}</h3>
      </div>
      <p style={{ fontSize: 14, color: "var(--fg-3)", lineHeight: 1.55, margin: 0 }}>{blurb}</p>
      {children && <div style={{ marginTop: 18 }}>{children}</div>}
      <div style={{ flex: 1 }} />
      <button
        className={active ? "btn btn-primary" : "btn btn-ghost"}
        disabled={confirmDisabled}
        onClick={(e) => { e.stopPropagation(); active ? onConfirm() : onSelect(); }}
        style={{
          marginTop: 18,
          justifyContent: "center",
          opacity: confirmDisabled ? 0.45 : 1,
          cursor: confirmDisabled ? "not-allowed" : "pointer",
        }}
      >
        {active ? cta : "Choose this"}
        <span aria-hidden style={{ fontFamily: "var(--font-mono)" }}>→</span>
      </button>
    </div>
  );
}

function TemplateList({ picked, onPick }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
      {FRAMEWORK.templates.map(t => {
        const active = picked && picked.id === t.id;
        return (
          <button
            key={t.id}
            onClick={(e) => { e.stopPropagation(); onPick(t); }}
            style={{
              appearance: "none",
              textAlign: "left",
              background: active ? "rgba(104,90,217,0.08)" : "transparent",
              border: `1px solid ${active ? "rgba(104,90,217,0.30)" : "transparent"}`,
              borderRadius: 10,
              padding: "9px 12px",
              cursor: "pointer",
              transition: "all 140ms var(--ease-out)",
            }}
            onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = "rgba(34,49,83,0.04)"; }}
            onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = "transparent"; }}
          >
            <div style={{
              display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 8,
            }}>
              <div style={{ fontFamily: "var(--font-jakarta)", fontWeight: 600, fontSize: 14 }}>{t.name}</div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fg-4)" }}>
                {t.lead.length}L · {t.follow.length}F
              </div>
            </div>
            <div style={{ fontSize: 12, color: "var(--fg-4)", marginTop: 2 }}>{t.tag}</div>
          </button>
        );
      })}
    </div>
  );
}

function LLMThinking() {
  return (
    <div style={{
      marginTop: 12,
      padding: "10px 14px",
      borderRadius: 10,
      background: "rgba(104,90,217,0.06)",
      border: "1px solid rgba(104,90,217,0.18)",
      fontSize: 12,
      color: "var(--c-violet-deep)",
      fontFamily: "var(--font-mono)",
      letterSpacing: "0.04em",
    }}>
      <span style={{
        display: "inline-block", width: 6, height: 6, borderRadius: 999,
        background: "var(--c-violet)", marginRight: 8, animation: "pulse 1.4s infinite"
      }}></span>
      Linus is reading…
    </div>
  );
}

function LLMReply({ reply, onAccept }) {
  return (
    <div style={{
      marginTop: 14,
      padding: 16,
      borderRadius: 12,
      background: "rgba(255,255,255,0.75)",
      border: "1px solid rgba(104,90,217,0.28)",
    }}>
      <div style={{
        fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase",
        color: "var(--c-violet-deep)", marginBottom: 8,
      }}>
        Linus → Closest template
      </div>
      <div style={{ fontFamily: "var(--font-jakarta)", fontWeight: 700, fontSize: 16, color: "var(--fg-1)" }}>
        {reply.template.name}
      </div>
      <div style={{ fontSize: 13, color: "var(--fg-3)", marginTop: 6, lineHeight: 1.5 }}>
        {reply.template.desc}
      </div>
      <div style={{
        marginTop: 14, padding: "12px 14px", borderRadius: 8,
        background: "rgba(34,49,83,0.04)", borderLeft: "2px solid var(--c-emerald)",
      }}>
        <div style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--fg-4)", marginBottom: 6, letterSpacing: "0.1em" }}>
          BEFORE WE OPEN THE FRAMEWORK
        </div>
        {reply.clarifiers.map((q, i) => (
          <div key={i} style={{ fontSize: 13.5, fontStyle: "italic", color: "var(--fg-2)", marginTop: i === 0 ? 0 : 6 }}>
            “{q}”
          </div>
        ))}
      </div>
      <button
        className="btn btn-primary"
        style={{ marginTop: 14, justifyContent: "center", width: "100%" }}
        onClick={(e) => { e.stopPropagation(); onAccept(); }}
      >
        Open with this template
        <span aria-hidden style={{ fontFamily: "var(--font-mono)" }}>→</span>
      </button>
    </div>
  );
}

window.Landing = Landing;
