/* Intake screen — compact, dense, sharp. Andy Price preloaded. */
const { useState: useStateIntake } = React;
const { TOKENS: T_INTAKE, Editable: EditableIntake, Tag: TagIntake, Tier: TierIntake, useViewport: useViewportIntake } = window.IE_UI;

function FieldRow({ label, hint, children, span = 1 }) {
  return (
    <div style={{ gridColumn: `span ${span}` }}>
      <div style={{
        fontFamily: T_INTAKE.mono, fontSize: 10, color: T_INTAKE.muted,
        textTransform: "uppercase", letterSpacing: ".08em", marginBottom: 5, fontWeight: 600,
      }}>{label}</div>
      {children}
      {hint && <div style={{ fontSize: 11, color: T_INTAKE.mutedDeep, marginTop: 4 }}>{hint}</div>}
    </div>
  );
}

function TextInput({ value, onChange, placeholder, type = "text" }) {
  return (
    <input
      type={type}
      value={value ?? ""}
      placeholder={placeholder}
      onChange={(e) => onChange(type === "number" ? Number(e.target.value) || null : e.target.value)}
      style={{
        width: "100%", background: T_INTAKE.bg, color: T_INTAKE.text,
        border: `1px solid ${T_INTAKE.border}`, borderRadius: 4, padding: "8px 10px",
        font: `13px ${T_INTAKE.sans}`, transition: "border-color .12s",
      }}
      onFocus={(e) => (e.target.style.borderColor = T_INTAKE.amber)}
      onBlur={(e) => (e.target.style.borderColor = T_INTAKE.border)}
    />
  );
}

function SelectInput({ value, onChange, options }) {
  return (
    <select
      value={value}
      onChange={(e) => onChange(e.target.value)}
      style={{
        width: "100%", background: T_INTAKE.bg, color: T_INTAKE.text,
        border: `1px solid ${T_INTAKE.border}`, borderRadius: 4, padding: "8px 10px",
        font: `13px ${T_INTAKE.sans}`, appearance: "none",
        backgroundImage: `linear-gradient(45deg, transparent 50%, ${T_INTAKE.muted} 50%), linear-gradient(135deg, ${T_INTAKE.muted} 50%, transparent 50%)`,
        backgroundPosition: `calc(100% - 14px) 14px, calc(100% - 9px) 14px`,
        backgroundSize: `5px 5px, 5px 5px`,
        backgroundRepeat: "no-repeat",
        paddingRight: 28,
      }}
    >
      {options.map((o) => <option key={o.value || o} value={o.value || o}>{o.label || o}</option>)}
    </select>
  );
}

function TextArea({ value, onChange, placeholder, rows = 3 }) {
  return (
    <textarea
      value={value ?? ""}
      placeholder={placeholder}
      rows={rows}
      onChange={(e) => onChange(e.target.value)}
      style={{
        width: "100%", background: T_INTAKE.bg, color: T_INTAKE.text,
        border: `1px solid ${T_INTAKE.border}`, borderRadius: 4, padding: "8px 10px",
        font: `13px/1.5 ${T_INTAKE.sans}`, resize: "vertical", transition: "border-color .12s",
      }}
      onFocus={(e) => (e.target.style.borderColor = T_INTAKE.amber)}
      onBlur={(e) => (e.target.style.borderColor = T_INTAKE.border)}
    />
  );
}

function IntakeBlock({ eyebrow, title, children }) {
  return (
    <div style={{ marginBottom: 22 }}>
      <div style={{ marginBottom: 10 }}>
        <div style={{
          fontFamily: T_INTAKE.mono, fontSize: 10, color: T_INTAKE.amberDim,
          textTransform: "uppercase", letterSpacing: ".12em", fontWeight: 600, marginBottom: 2,
        }}>{eyebrow}</div>
        <div style={{ font: `600 15px/1.2 ${T_INTAKE.sans}`, color: T_INTAKE.text, letterSpacing: "-0.01em" }}>{title}</div>
      </div>
      {children}
    </div>
  );
}

function MarketRow({ row, onChange, onRemove, isMobile }) {
  const set = (k) => (v) => onChange({ ...row, [k]: v });
  if (isMobile) {
    const labelStyle = {
      fontFamily: T_INTAKE.mono, fontSize: 10, color: T_INTAKE.muted,
      textTransform: "uppercase", letterSpacing: ".08em", fontWeight: 600,
      marginBottom: 4, display: "block",
    };
    return (
      <div style={{
        position: "relative",
        padding: "12px 12px 14px", marginBottom: 10,
        background: T_INTAKE.panel, border: `1px solid ${T_INTAKE.borderSoft}`, borderRadius: 6,
      }}>
        <button onClick={onRemove} style={{
          position: "absolute", top: 6, right: 8,
          background: "transparent", border: "none", color: T_INTAKE.mutedDeep,
          cursor: "pointer", fontSize: 18, padding: "4px 6px", lineHeight: 1,
        }}>×</button>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 10 }}>
          <div>
            <span style={labelStyle}>Tier</span>
            <SelectInput value={row.tier} onChange={set("tier")} options={window.IE_DATA.TIERS} />
          </div>
          <div>
            <span style={labelStyle}>State</span>
            <SelectInput value={row.state} onChange={set("state")} options={window.IE_DATA.STATES} />
          </div>
        </div>
        <div style={{ marginBottom: 10 }}>
          <span style={labelStyle}>Company</span>
          <TextInput value={row.company} onChange={set("company")} placeholder="Company" />
        </div>
        <div style={{ marginBottom: 10 }}>
          <span style={labelStyle}>Reason</span>
          <TextInput value={row.reason} onChange={set("reason")} placeholder="State reason / why target" />
        </div>
        <div>
          <span style={labelStyle}>Classification</span>
          <SelectInput value={row.classification} onChange={set("classification")} options={window.IE_DATA.CLASSIFICATIONS} />
        </div>
      </div>
    );
  }
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: "82px 1fr 160px 1.2fr 140px 24px",
      gap: 8, padding: "6px 0", alignItems: "center",
    }}>
      <SelectInput value={row.tier} onChange={set("tier")} options={window.IE_DATA.TIERS} />
      <TextInput value={row.company} onChange={set("company")} placeholder="Company" />
      <SelectInput value={row.state} onChange={set("state")} options={window.IE_DATA.STATES} />
      <TextInput value={row.reason} onChange={set("reason")} placeholder="State reason / why target" />
      <SelectInput value={row.classification} onChange={set("classification")} options={window.IE_DATA.CLASSIFICATIONS} />
      <button onClick={onRemove} style={{
        background: "transparent", border: "none", color: T_INTAKE.mutedDeep,
        cursor: "pointer", fontSize: 16, padding: 0,
      }} onMouseEnter={(e) => (e.target.style.color = T_INTAKE.danger)}
         onMouseLeave={(e) => (e.target.style.color = T_INTAKE.mutedDeep)}>×</button>
    </div>
  );
}

function Intake({ intake, setIntake, onGenerate }) {
  const { isMobile } = useViewportIntake();
  const set = (k) => (v) => setIntake({ ...intake, [k]: v });
  const setLines = (k) => (v) => setIntake({ ...intake, [k]: v.split("\n").map(s => s.trim()).filter(Boolean) });

  const updateMarketRow = (idx, row) => {
    const next = [...intake.market];
    next[idx] = row;
    setIntake({ ...intake, market: next });
  };
  const removeMarketRow = (idx) => {
    setIntake({ ...intake, market: intake.market.filter((_, i) => i !== idx) });
  };
  const addMarketRow = () => {
    setIntake({ ...intake, market: [...intake.market, { tier: "Tier 2", company: "", state: "Stable", reason: "", classification: "Recruiter-Supplied" }] });
  };

  return (
    <div style={{ maxWidth: 980, margin: "0 auto", padding: isMobile ? "20px 16px 60px" : "32px 40px 80px" }}>
      <div style={{ marginBottom: 28, display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 14 }}>
        <div>
          <div style={{
            fontFamily: T_INTAKE.mono, fontSize: 10.5, color: T_INTAKE.amberDim,
            letterSpacing: ".12em", textTransform: "uppercase", fontWeight: 600, marginBottom: 4,
          }}>Phase 01 — Intake</div>
          <h2 style={{ font: `600 26px/1.15 ${T_INTAKE.serif}`, margin: 0, letterSpacing: "-0.015em" }}>Search Intake</h2>
          <p style={{ color: T_INTAKE.textDim, maxWidth: 600, margin: "8px 0 0", fontSize: 13 }}>
            Thirty minutes of structured prep. Fill what you know.
            What you don't know reads <span style={{ fontFamily: T_INTAKE.mono, color: T_INTAKE.warn }}>requires validation in kickoff</span> — never fabricated.
          </p>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button onClick={() => setIntake(window.IE_DATA.ANDY_CASE)} style={{
            background: "transparent", color: T_INTAKE.textDim, border: `1px solid ${T_INTAKE.border}`,
            padding: "9px 14px", borderRadius: 4, font: `12px ${T_INTAKE.sans}`, fontWeight: 500, cursor: "pointer",
          }}>Reload proof case</button>
          <button onClick={onGenerate} style={{
            background: T_INTAKE.amber, color: "#1a1a1a", border: "none",
            padding: "9px 18px", borderRadius: 4, font: `13px ${T_INTAKE.sans}`, fontWeight: 600, cursor: "pointer",
            letterSpacing: ".01em",
          }}>Run Diagnostic →</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1.4fr 1fr", gap: isMobile ? 0 : 28 }}>
        <div>
          <IntakeBlock eyebrow="01" title="Search">
            <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 12, marginBottom: 12 }}>
              <FieldRow label="Role title"><TextInput value={intake.role_title} onChange={set("role_title")} placeholder="e.g. CFO" /></FieldRow>
              <FieldRow label="Role family"><SelectInput value={intake.role_family} onChange={set("role_family")} options={["CFO","VP Sales","Product","Engineering","Ops","Other"]} /></FieldRow>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 12, marginBottom: 12 }}>
              <FieldRow label="Company name"><TextInput value={intake.company} onChange={set("company")} /></FieldRow>
              <FieldRow label="Industry"><TextInput value={intake.industry} onChange={set("industry")} placeholder="e.g. industrial services, vertical SaaS" /></FieldRow>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr 1fr", gap: 12 }}>
              <FieldRow label="Ownership"><SelectInput value={intake.ownership} onChange={set("ownership")} options={["PE-backed","VC-backed","founder-owned","public","other"]} /></FieldRow>
              <FieldRow label="Stage"><SelectInput value={intake.stage} onChange={set("stage")} options={["startup","growth","mid-market","enterprise","turnaround"]} /></FieldRow>
              <FieldRow label="Tier"><SelectInput value={intake.tier} onChange={set("tier")} options={["Boutique","Mid-Market","Enterprise"]} /></FieldRow>
            </div>
          </IntakeBlock>

          <IntakeBlock eyebrow="02" title="Geography & Timeline">
            <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 12, marginBottom: 12 }}>
              <FieldRow label="Geography"><TextInput value={intake.geography} onChange={set("geography")} placeholder="e.g. Cleveland, OH" /></FieldRow>
              <FieldRow label="Remote policy"><SelectInput value={intake.remote_policy} onChange={set("remote_policy")} options={[{value:"onsite",label:"Onsite (5 days)"},{value:"hybrid",label:"Hybrid (2–3 days)"},{value:"remote",label:"Remote"}]} /></FieldRow>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 12 }}>
              <FieldRow label="Timeline (weeks)"><TextInput value={intake.timeline_weeks} onChange={set("timeline_weeks")} type="number" /></FieldRow>
              <FieldRow label="Confidential search"><SelectInput value={intake.confidential ? "yes" : "no"} onChange={(v) => set("confidential")(v === "yes")} options={[{value:"no",label:"No"},{value:"yes",label:"Yes"}]} /></FieldRow>
            </div>
          </IntakeBlock>

          <IntakeBlock eyebrow="03" title="Compensation">
            <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr 1fr" : "1fr 1fr 1fr 1fr", gap: 12, marginBottom: 12 }}>
              <FieldRow label="Cash low"><TextInput value={intake.cash_low} onChange={set("cash_low")} type="number" placeholder="USD" /></FieldRow>
              <FieldRow label="Cash high"><TextInput value={intake.cash_high} onChange={set("cash_high")} type="number" placeholder="USD" /></FieldRow>
              <FieldRow label="TC low"><TextInput value={intake.tc_low} onChange={set("tc_low")} type="number" placeholder="USD" /></FieldRow>
              <FieldRow label="TC high"><TextInput value={intake.tc_high} onChange={set("tc_high")} type="number" placeholder="USD" /></FieldRow>
            </div>
            <FieldRow label="Comp friction notes (optional)"><TextInput value={intake.comp_notes} onChange={set("comp_notes")} placeholder="e.g. sign-on capped, vest schedule below market" /></FieldRow>
          </IntakeBlock>

          <IntakeBlock eyebrow="04" title="Mandate">
            <FieldRow label="Why this role, why now (2–4 sentences)">
              <TextArea value={intake.mandate} onChange={set("mandate")} rows={3} />
            </FieldRow>
            <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 12, marginTop: 12 }}>
              <FieldRow label="Must-haves (one per line)">
                <TextArea value={(intake.must_haves || []).join("\n")} onChange={setLines("must_haves")} rows={5} />
              </FieldRow>
              <FieldRow label="Nice-to-haves (one per line)">
                <TextArea value={(intake.nice_to_haves || []).join("\n")} onChange={setLines("nice_to_haves")} rows={5} />
              </FieldRow>
            </div>
            <div style={{ marginTop: 12 }}>
              <FieldRow label="Recent operating pressure (last 12 months)">
                <TextArea value={intake.company_events} onChange={set("company_events")} rows={3} placeholder="e.g. 18 months post-LBO, ERP migration, exit window H2 2027" />
              </FieldRow>
            </div>
          </IntakeBlock>
        </div>

        <div>
          <IntakeBlock eyebrow="05" title="Hiring Manager">
            <div style={{ marginBottom: 12 }}>
              <FieldRow label="HM name & title"><TextInput value={intake.hm_name} onChange={set("hm_name")} /></FieldRow>
            </div>
            <div style={{ marginBottom: 12 }}>
              <FieldRow label="HM calibration (self-rated)">
                <SelectInput value={intake.hm_cal} onChange={set("hm_cal")} options={[
                  { value: "High", label: "High — knows what they want" },
                  { value: "Medium", label: "Medium — directionally clear" },
                  { value: "Low", label: "Low — needs education first" },
                ]} />
              </FieldRow>
            </div>
            <FieldRow label="Observed behavior" hint="Recruiter-supplied. No personality speculation.">
              <TextArea value={intake.hm_notes} onChange={set("hm_notes")} rows={5} />
            </FieldRow>
          </IntakeBlock>

          <IntakeBlock eyebrow="06" title="Context">
            <FieldRow label="Past failure modes (if known)">
              <TextArea value={intake.past_failures} onChange={set("past_failures")} rows={3} />
            </FieldRow>
            <div style={{ marginTop: 12 }}>
              <FieldRow label="Sponsor / board / sourcing context">
                <TextArea value={intake.other_context} onChange={set("other_context")} rows={3} />
              </FieldRow>
            </div>
            <div style={{ marginTop: 12 }}>
              <FieldRow label="Off-limits companies (one per line)">
                <TextArea value={(intake.off_limits || []).join("\n")} onChange={setLines("off_limits")} rows={3} />
              </FieldRow>
            </div>
          </IntakeBlock>
        </div>
      </div>

      <IntakeBlock eyebrow="07" title="Market State Map — initial targets">
        <div style={{
          fontSize: 12, color: T_INTAKE.textDim, marginBottom: 10,
          padding: "8px 12px", background: T_INTAKE.panel, border: `1px solid ${T_INTAKE.borderSoft}`, borderRadius: 4,
          lineHeight: 1.5,
        }}>
          State language: <span style={{ fontFamily: T_INTAKE.mono, color: T_INTAKE.amber }}>Frozen · Post-leadership-change · Pre-restructure · Post-restructure · Post-liquidity · Pre-liquidity · Distressed · Flush · Stable · Off-limits</span>
        </div>
        {!isMobile && (
          <div style={{
            display: "grid", gridTemplateColumns: "82px 1fr 160px 1.2fr 140px 24px",
            gap: 8, padding: "6px 0", alignItems: "center",
            fontFamily: T_INTAKE.mono, fontSize: 10, color: T_INTAKE.muted,
            textTransform: "uppercase", letterSpacing: ".08em", borderBottom: `1px solid ${T_INTAKE.borderSoft}`,
          }}>
            <div>Tier</div><div>Company</div><div>State</div><div>Reason</div><div>Classification</div><div></div>
          </div>
        )}
        {intake.market.map((row, idx) => (
          <MarketRow key={idx} row={row} onChange={(r) => updateMarketRow(idx, r)} onRemove={() => removeMarketRow(idx)} isMobile={isMobile} />
        ))}
        <button onClick={addMarketRow} style={{
          background: "transparent", color: T_INTAKE.blue, border: `1px dashed ${T_INTAKE.border}`,
          padding: "8px 14px", borderRadius: 4, font: `12px ${T_INTAKE.sans}`, cursor: "pointer", marginTop: 8,
        }}>+ Add company</button>
      </IntakeBlock>

      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        padding: "20px 0 0", borderTop: `1px solid ${T_INTAKE.border}`, marginTop: 20,
      }}>
        <div style={{ fontSize: 11, color: T_INTAKE.muted, fontFamily: T_INTAKE.mono, letterSpacing: ".04em" }}>
          Session 1 · Direction frozen · v2.1 spec
        </div>
        <button onClick={onGenerate} style={{
          background: T_INTAKE.amber, color: "#1a1a1a", border: "none",
          padding: "11px 20px", borderRadius: 4, font: `13px ${T_INTAKE.sans}`, fontWeight: 600, cursor: "pointer",
        }}>Run Diagnostic + Generate Brief →</button>
      </div>
    </div>
  );
}

window.IE_INTAKE = { Intake };
