// Step 1 — Prospect Basics (+ URLs, + upload-to-autofill)

function Step1({ form, setForm, onNext, onImportUseCases }) {
  const { INDUSTRIES, HEADCOUNT, LANGS } = window.TB_DATA;
  const [importState, setImportState] = React.useState(null); // null | {fileName, evidence, ucCount}
  const [dragging, setDragging] = React.useState(false);
  const [error, setError] = React.useState("");
  const [touched, setTouched] = React.useState({});
  const [attemptedNext, setAttemptedNext] = React.useState(false);
  const [showSetup, setShowSetup] = React.useState(false);

  const isUrl = (s) => {
    if (!s) return false;
    try { const u = new URL(/^https?:\/\//i.test(s) ? s : `https://${s}`); return !!u.hostname.includes("."); } catch { return false; }
  };
  const isEmail = (s) => !s || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s);

  const fieldErrors = {
    company: !form.company.trim() ? "Company name required" : "",
    websiteUrl: !form.websiteUrl ? "Website URL required" : !isUrl(form.websiteUrl) ? "Not a valid URL" : "",
    careerUrl: !form.careerUrl ? "Career page URL required" : !isUrl(form.careerUrl) ? "Not a valid URL" : "",
    language: !form.language ? "Language required" : "",
    aeName: !form.aeName ? "AE name required" : "",
    contactEmail: !isEmail(form.contactEmail) ? "Not a valid email" : "",
  };
  const missingCount = Object.values(fieldErrors).filter(Boolean).length;
  const valid = missingCount === 0;
  const show = (k) => (touched[k] || attemptedNext) && fieldErrors[k];

  const blur = (k) => () => setTouched(t => ({ ...t, [k]: true }));
  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const handleNext = () => {
    if (valid) return onNext();
    setAttemptedNext(true);
    setTimeout(() => {
      const el = document.querySelector(".field.err");
      if (el) {
        const rect = el.getBoundingClientRect();
        window.scrollTo({ top: window.scrollY + rect.top - 120, behavior: "smooth" });
      }
    }, 50);
  };

  async function handleLogo(file) {
    if (!file) return;
    if (!/^image\//.test(file.type)) { setError("Logo must be an image."); return; }
    const reader = new FileReader();
    reader.onload = () => setForm({ ...form, logoDataUrl: reader.result });
    reader.readAsDataURL(file);
  }

  async function handleFile(file) {
    setError("");
    if (!file) return;
    if (!/\.html?$/i.test(file.name) && file.type !== "text/html") {
      setError("Please upload an .html prep guide.");
      return;
    }
    const text = await file.text();
    try {
      const { fields, selectedUseCases, evidence } = window.parsePrepGuide(text);
      // merge fields into form (don't overwrite non-empty user input)
      const merged = { ...form };
      for (const [k, v] of Object.entries(fields)) {
        if (v && !merged[k]) merged[k] = v;
      }
      setForm(merged);
      if (selectedUseCases.length) onImportUseCases(selectedUseCases);
      setImportState({ fileName: file.name, evidence, ucCount: selectedUseCases.length });
    } catch (e) {
      setError("Couldn't parse that file. It doesn't match the expected prep-guide format.");
    }
  }

  return (
    <div className="fade-enter">

      {/* Upload affordance */}
      <div
        className={`drop ${dragging ? "drag" : ""} ${importState ? "done" : ""}`}
        onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
        onDragLeave={() => setDragging(false)}
        onDrop={(e) => {
          e.preventDefault(); setDragging(false);
          const f = e.dataTransfer.files?.[0];
          if (f) handleFile(f);
        }}>
        <div className="drop-icon" aria-hidden>
          <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/>
          </svg>
        </div>
        <div className="drop-body">
          {!importState ? (
            <>
              <div className="drop-title">Drop an AE prep guide to autofill</div>
              <div className="drop-sub">HTML file (e.g. the EQS-style prep guide). We'll extract company, industry, headcount, language, ATS, URLs — and pre-select recommended use cases.</div>
            </>
          ) : (
            <>
              <div className="drop-title">Imported from <span className="drop-file">{importState.fileName}</span></div>
              <div className="drop-sub">
                {importState.ucCount} use case{importState.ucCount === 1 ? "" : "s"} pre-selected · {importState.evidence.length} fields detected
              </div>
            </>
          )}
        </div>
        <div className="drop-actions">
          <label className="btn btn-primary">
            <input type="file" accept=".html,.htm,text/html" style={{ display: "none" }}
              onChange={(e) => handleFile(e.target.files?.[0])} />
            {importState ? "Replace" : "Choose file"}
          </label>
          {importState && (
            <button className="btn btn-ghost" onClick={() => setImportState(null)}>Clear</button>
          )}
        </div>
      </div>

      {/* Research-in-Claude shortcut */}
      <div style={{ margin: "12px 0 4px", background: "var(--surface)", borderRadius: "var(--radius)", boxShadow: "var(--shadow-sm)", overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 16px" }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)", marginBottom: 2 }}>No prep guide yet?</div>
            <div style={{ fontSize: 12, color: "var(--ink-4)", lineHeight: 1.5 }}>
              Run the prospect intelligence skill in Claude Cowork — it produces the prep guide you can drop above to autofill this form.{" "}
              <button
                onClick={() => setShowSetup(s => !s)}
                style={{ background: "none", border: "none", padding: 0, font: "inherit", fontSize: 12, color: "var(--green-700)", cursor: "pointer", textDecoration: "underline", textUnderlineOffset: 2 }}
              >
                {showSetup ? "Hide setup" : "First time? See setup steps"}
              </button>
            </div>
          </div>
          <button
            className="btn btn-primary"
            style={{ whiteSpace: "nowrap", flexShrink: 0 }}
            title={!form.company.trim() ? "Enter a company name first" : "Open Claude with a pre-filled prompt"}
            onClick={() => {
              const company = form.company.trim();
              const prompt = [
                company
                  ? `Run prospect intelligence for Talentry demo prep: ${company}`
                  : "Run the prospect intelligence skill for a new Talentry demo prospect",
                form.websiteUrl && `Website: ${form.websiteUrl}`,
                form.careerUrl && `Career page: ${form.careerUrl}`,
                "Produce the AE prep guide as an HTML file I can download and import into the Tenant Builder."
              ].filter(Boolean).join(". ");
              window.open(`https://claude.ai/new?q=${encodeURIComponent(prompt)}`, "_blank");
            }}
          >
            Research in Claude →
          </button>
        </div>

        {showSetup && (
          <div style={{ borderTop: "1px solid var(--border)", padding: "12px 16px 14px", display: "flex", flexDirection: "column", gap: 8 }}>
            {[
              {
                n: "1",
                title: "Install the CleverConnect Cowork plugin",
                body: <>Download the plugin from the <a href="/setup" target="_blank" rel="noopener noreferrer" style={{ color: "var(--green-700)" }}>setup page</a> and install it in Claude Cowork (desktop app).</>
              },
              {
                n: "2",
                title: "Enter a company name above (optional but recommended)",
                body: "If you fill in the company name — and ideally the website URL — before clicking the button, Claude gets a pre-filled prompt that triggers the skill automatically."
              },
              {
                n: "3",
                title: "Click \"Research in Claude →\" and let the skill run",
                body: "Claude will research the prospect, pick the best-fit use cases, and produce an AE prep guide HTML file. Download it, then drop it into the upload zone above."
              }
            ].map(({ n, title, body }) => (
              <div key={n} style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
                <div style={{ width: 20, height: 20, borderRadius: "50%", background: "var(--green-700)", color: "#fff", fontSize: 11, fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, marginTop: 1 }}>{n}</div>
                <div style={{ fontSize: 12, lineHeight: 1.55, color: "var(--ink-3)" }}>
                  <span style={{ fontWeight: 600, color: "var(--ink)", display: "block", marginBottom: 1 }}>{title}</span>
                  {body}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {importState && importState.evidence.length > 0 && (
        <div className="import-evidence fade-enter">
          <div className="col-label">Detected values</div>
          <div className="evidence-grid">
            {importState.evidence.map((e, i) => {
              const [k, ...rest] = e.split(":");
              return (
                <div key={i} className="ev">
                  <div className="ev-k">{k.trim()}</div>
                  <div className="ev-v">{rest.join(":").trim()}</div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {error && <div className="drop-error">{error}</div>}

      <div className="card" style={{ marginTop: 20 }}>
        <div className="form-grid">
          <div className="field full">
            <label>Company name <span className="req">*</span></label>
            <input className={`input ${show("company") ? "input-err" : ""}`} placeholder="e.g. Northwind Logistics"
              value={form.company} onChange={set("company")} onBlur={blur("company")} autoFocus />
            {show("company")
              ? <span className="err-msg">{fieldErrors.company}</span>
              : <span className="hint">Used as the prefix in generated names across all use cases.</span>}
          </div>

          <div className={`field ${show("websiteUrl") ? "err" : ""}`}>
            <label>Prospect website URL <span className="req">*</span></label>
            <input className={`input ${show("websiteUrl") ? "input-err" : ""}`} placeholder="https://company.com"
              value={form.websiteUrl || ""} onChange={set("websiteUrl")} onBlur={blur("websiteUrl")} />
            {show("websiteUrl")
              ? <span className="err-msg">{fieldErrors.websiteUrl}</span>
              : <span className="hint">Used for research and the handoff brief.</span>}
          </div>

          <div className={`field ${show("careerUrl") ? "err" : ""}`}>
            <label>Career page URL <span className="req">*</span></label>
            <input className={`input ${show("careerUrl") ? "input-err" : ""}`} placeholder="https://company.com/careers"
              value={form.careerUrl || ""} onChange={set("careerUrl")} onBlur={blur("careerUrl")} />
            {show("careerUrl")
              ? <span className="err-msg">{fieldErrors.careerUrl}</span>
              : <span className="hint">Needed to map open roles into the demo tenant.</span>}
          </div>

          <div className="field">
            <label>Industry</label>
            <select className="select" value={form.industry} onChange={set("industry")}>
              <option value="">Select industry…</option>
              {INDUSTRIES.map(i => <option key={i}>{i}</option>)}
            </select>
          </div>

          <div className="field">
            <label>Headcount</label>
            <select className="select" value={form.headcount} onChange={set("headcount")}>
              <option value="">Select headcount…</option>
              {HEADCOUNT.map(h => <option key={h}>{h}</option>)}
            </select>
          </div>

          <div className="field">
            <label>Language <span className="req">*</span></label>
            <div className="seg" role="radiogroup" aria-label="Language">
              {LANGS.map(l => (
                <button key={l.k}
                  aria-pressed={form.language === l.k}
                  onClick={() => setForm({ ...form, language: l.k })}>
                  {l.k} <span style={{ color: "var(--ink-4)", marginLeft: 4, fontSize: 12 }}>{l.label}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="field">
            <label>ATS in use</label>
            <input className="input" placeholder="e.g. Personio, Workday, Greenhouse…"
              value={form.ats} onChange={set("ats")} />
            <span className="hint">Free text — used on the handoff brief.</span>
          </div>

          <div className="field">
            <label>Country / region</label>
            <input className="input" placeholder="e.g. Germany, DACH, EU"
              value={form.country || ""} onChange={set("country")} />
            <span className="hint">Drives GDPR jurisdiction + regional ATS notes.</span>
          </div>

          <div className="field">
            <label>Demo date</label>
            <input className="input" type="date"
              value={form.demoDate || ""} onChange={set("demoDate")} />
            <span className="hint">Builds urgency + surfaces on the tenant name.</span>
          </div>

          <div className={`field ${show("aeName") ? "err" : ""}`}>
            <label>AE / owner <span className="req">*</span></label>
            <input className={`input ${show("aeName") ? "input-err" : ""}`} placeholder="e.g. Levent Goebel"
              value={form.aeName || ""} onChange={set("aeName")} onBlur={blur("aeName")} />
            {show("aeName")
              ? <span className="err-msg">{fieldErrors.aeName}</span>
              : <span className="hint">Who's building this tenant. Used on handoff emails.</span>}
          </div>

          <div className="field">
            <label>Prospect logo <span style={{ color: "var(--ink-4)", fontWeight: 400 }}>(optional)</span></label>
            <div className="logo-row">
              <div className="logo-preview" aria-hidden>
                {form.logoDataUrl
                  ? <img src={form.logoDataUrl} alt="" />
                  : <span className="logo-placeholder">LOGO</span>}
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 6, flex: 1 }}>
                <label className="btn btn-sec" style={{ alignSelf: "flex-start" }}>
                  <input type="file" accept="image/*" style={{ display: "none" }}
                    onChange={(e) => handleLogo(e.target.files?.[0])} />
                  {form.logoDataUrl ? "Replace logo" : "Upload logo"}
                </label>
                {form.logoDataUrl && (
                  <button className="btn btn-ghost" style={{ alignSelf: "flex-start", padding: "4px 8px", fontSize: 12 }}
                    onClick={() => setForm({ ...form, logoDataUrl: "" })}>Remove</button>
                )}
                <span className="hint">Makes the demo feel like their tenant. PNG / SVG.</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <FooterActions
        left={<>
          <span className="count-pill">Step 1 of 3</span>
          {missingCount > 0
            ? <span className="miss-chip">{missingCount} field{missingCount === 1 ? "" : "s"} to complete</span>
            : <span style={{ color: "var(--green-700)", fontSize: 13, display: "inline-flex", alignItems: "center", gap: 6 }}><Ic.check /> All set</span>}
        </>}
        primaryLabel={<>Next <Ic.arrow /></>}
        primaryDisabled={false}
        onPrimary={handleNext}
      />
    </div>
  );
}

function FooterActions({ left, primaryLabel, primaryDisabled, onPrimary, onBack, secondary }) {
  return (
    <div className="foot">
      <div className="foot-inner">
        <div className="foot-left">{left}</div>
        <div className="foot-right">
          {onBack && <button className="btn btn-ghost" onClick={onBack}><Ic.arrowL /> Back</button>}
          {secondary}
          <button className="btn btn-primary" disabled={primaryDisabled} onClick={onPrimary}>
            {primaryLabel}
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Step1, FooterActions });
