// src/ui/steps/step1-rol.jsx — omschrijf opdracht + AI rol-suggestie

const StepRol = ({ state, setState, next, back }) => {
  const huidige = state.rollen?.[0];
  const [omschrijving, setOmschrijving] = React.useState(state.omschrijving || "");
  React.useEffect(() => {
    setState(s => s.omschrijving === omschrijving ? s : { ...s, omschrijving });
  }, [omschrijving]);
  const [suggesties, setSuggesties] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [aiError, setAiError] = React.useState(false);
  const [manual, setManual] = React.useState(false);
  const [selectedRol, setSelectedRol] = React.useState(huidige?.rol || null);
  const [selectedDep, setSelectedDep] = React.useState(null);
  const [searchQuery, setSearchQuery] = React.useState("");

  const isFestival = state.type === "festival";
  const rollen = isFestival ? window.ROLLEN_FESTIVAL : window.ROLLEN_FILM_AV;

  const aiCtrlRef = React.useRef(null);
  React.useEffect(() => () => aiCtrlRef.current?.abort(), []);

  const vraagAI = async () => {
    if (!omschrijving.trim() || omschrijving.trim().length < 10) return;
    aiCtrlRef.current?.abort();
    const ctrl = new AbortController();
    aiCtrlRef.current = ctrl;
    setLoading(true);
    setSuggesties(null);
    setAiError(false);
    const res = await window.aiHelp.suggestRol(omschrijving, isFestival, { signal: ctrl.signal });
    if (ctrl.signal.aborted) return;
    setLoading(false);
    if (res) setSuggesties(res);
    else { setAiError(true); setManual(true); }
  };

  const kies = (rol) => {
    setSelectedRol(rol);
  };

  const verderMet = (rolObj) => {
    const bestaande = state.rollen?.[0];
    const wisseltRol = bestaande && bestaande.rol !== rolObj.rol;
    const nieuwId = window.crypto?.randomUUID?.() || `r-${Date.now()}`;
    const nieuweRol = {
      id: wisseltRol ? nieuwId : (bestaande?.id || nieuwId),
      rol: rolObj.rol,
      dep: rolObj.dep,
      niveau: rolObj.niveau,
      niveau_bron: "rol-lookup",
      uren: wisseltRol
        ? { hoofdwerk: 0, voorbereiding: 0, afronding: 0, pr_promotie: 0 }
        : (bestaande?.uren || { hoofdwerk: 0, voorbereiding: 0, afronding: 0, pr_promotie: 0 }),
      urenDetails: wisseltRol ? undefined : bestaande?.urenDetails,
      onderhandelsignalen: wisseltRol ? [] : (bestaande?.onderhandelsignalen || []),
    };
    setState(s => ({
      ...s,
      omschrijving,
      rollen: [nieuweRol],
    }));
    next();
  };

  const departementen = [...new Set(rollen.map(r => r.dep))];
  const omschrijvingVoor = (dep, rolNaam) =>
    rollen.find(x => x.dep === dep && x.rol === rolNaam)?.omschrijving || "";
  const gefilterdeRollen = rollen.filter(r => {
    if (selectedDep && r.dep !== selectedDep) return false;
    if (searchQuery) {
      const q = searchQuery.toLowerCase();
      return r.rol.toLowerCase().includes(q) || r.dep.toLowerCase().includes(q);
    }
    return true;
  });

  return (
    <div>
      <StepHeader
        tag={isFestival ? "Filmfestival" : "Filmproductie"}
        title="Vertel ons over je opdracht"
        sub="Beschrijf je opdracht in een paar zinnen — wat ga je precies doen? We gebruiken je omschrijving om je rol en het bijbehorende zwaarteniveau voor te stellen."
      />

      <div className="row-2col" style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 24, alignItems: "start" }}>
        <div>
          <FwTextarea
            label="Omschrijving van de opdracht"
            placeholder={isFestival
              ? "Bijv: Ik coördineer de programmering voor een internationaal documentaire-festival in Amsterdam, 4 festivaldagen, ongeveer 40 films."
              : "Bijv: Ik ben 1st AC op een Nederlandse speelfilm, 32 draaidagen, veel nachtopnames in Rotterdam, ervaren team."}
            rows={6}
            value={omschrijving}
            onChange={e => setOmschrijving(e.target.value)}
            hint={`${omschrijving.length} tekens — meer detail = betere suggestie`}
          />
          <div style={{ marginTop: 16, display: "flex", gap: 12, alignItems: "center" }}>
            <FwButton variant="primary" icon="ri-sparkling-2-line" arrow={false}
              onClick={vraagAI} disabled={loading || omschrijving.trim().length < 10}>
              {loading ? "Even denken…" : "Stel een rol voor"}
            </FwButton>
            <button onClick={() => setManual(true)} style={{
              background: "transparent", border: 0, color: FW.navy, fontWeight: 700, fontSize: 15,
              cursor: "pointer", textDecoration: "underline", textDecorationThickness: 2, textUnderlineOffset: 4,
            }}>of kies zelf uit de lijst →</button>
          </div>

          {aiError && (
            <FwInlineBanner type="warning" onDismiss={() => setAiError(false)} style={{ marginTop: 14 }}>
              <div style={{ fontWeight: 700, marginBottom: 4 }}>AI-suggestie mislukt — kies je rol via de lijst hieronder.</div>
              {window.__lastAiError && (
                <div style={{ fontSize: 13, color: FW.navy2, fontFamily: "ui-monospace, monospace" }}>
                  {window.__lastAiError}
                </div>
              )}
            </FwInlineBanner>
          )}

          {suggesties && (
            <div style={{ marginTop: 24, padding: 20, background: "#FEF9B3", borderRadius: 16, border: `1.5px solid ${FW.yellow}` }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10, fontSize: 13, fontWeight: 700, textTransform: "uppercase", letterSpacing: 0.5, color: FW.navy }}>
                <i className="ri-sparkling-2-line" /> Voorstel op basis van je omschrijving
              </div>
              <div style={{ fontSize: 15, color: FW.navy2, marginBottom: 16, lineHeight: 1.45 }}>{suggesties.toelichting}</div>
              <div style={{ display: "grid", gap: 10 }}>
                {suggesties.top_rollen?.map((r, i) => (
                  <button key={i} onClick={() => verderMet(r)} style={rolCard(i === 0)}>
                    <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
                      <div style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 18, fontWeight: 700, color: FW.navy }}>
                        {r.rol}
                        <RolTooltip tekst={omschrijvingVoor(r.dep, r.rol)} />
                      </div>
                      <div style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                        <NiveauBadge niveau={r.niveau} />
                        <span style={{ fontSize: 14, color: FW.gray500 }}>{r.dep}</span>
                      </div>
                    </div>
                    <div style={{ fontSize: 14, color: FW.navy2, marginTop: 4 }}>{r.reden}</div>
                    <div style={{ marginTop: 10, fontSize: 14, fontWeight: 700, color: FW.navy, display: "inline-flex", alignItems: "center", gap: 6 }}>
                      Kies deze rol <span style={{ display: "inline-grid", placeItems: "center", width: 22, height: 22, borderRadius: 999, background: FW.navy, color: "#fff", fontSize: 12 }}>→</span>
                    </div>
                  </button>
                ))}
              </div>
            </div>
          )}

          {manual && (
            <div style={{ marginTop: 24, padding: 20, background: FW.cream, borderRadius: 16, border: `1.5px solid ${FW.gray100}` }}>
              <div style={{ fontSize: 18, fontWeight: 700, marginBottom: 12 }}>Kies uit de rollen-lijst</div>
              <FwInput placeholder="Zoek op rol of departement..."
                value={searchQuery} onChange={e => setSearchQuery(e.target.value)}
                containerStyle={{ marginBottom: 12 }} />
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 14 }}>
                <FwChip active={!selectedDep} onClick={() => setSelectedDep(null)}>Alle</FwChip>
                {departementen.map(d => (
                  <FwChip key={d} active={selectedDep === d} onClick={() => setSelectedDep(selectedDep === d ? null : d)}>{d}</FwChip>
                ))}
              </div>
              <div style={{ maxHeight: 300, overflowY: "auto", display: "grid", gap: 6 }}>
                {gefilterdeRollen.map((r, i) => (
                  <button key={i} onClick={() => verderMet(r)} style={{
                    display: "flex", justifyContent: "space-between", alignItems: "center",
                    padding: "10px 14px", background: FW.white, border: `1px solid ${FW.gray100}`,
                    borderRadius: 10, cursor: "pointer", fontFamily: "var(--font-sans)",
                    textAlign: "left",
                  }}>
                    <div>
                      <div style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 15, fontWeight: 700, color: FW.navy }}>
                        {r.rol}
                        <RolTooltip tekst={r.omschrijving} />
                      </div>
                      <div style={{ fontSize: 13, color: FW.gray500 }}>{r.dep}</div>
                    </div>
                    <NiveauBadge niveau={r.niveau} />
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>

        <AsideCard>
          <div style={{ fontSize: 14, fontWeight: 700, color: FW.navy, marginBottom: 10, display: "inline-flex", alignItems: "center", gap: 6 }}>
            <i className="ri-lightbulb-line" /> Tip
          </div>
          <div style={{ fontSize: 15, lineHeight: 1.5, color: FW.navy2 }}>
            Noem vooral: <b>wat je rol is</b>, <b>hoe groot de productie</b> is (budget, crew, draaidagen), <b>hoe zelfstandig</b> je werkt, en of er <b>bijzondere omstandigheden</b> zijn (nachten, reizen, meerdere locaties).
          </div>
          <div style={{ marginTop: 16, padding: 14, background: FW.cream, borderRadius: 12, fontSize: 13, color: FW.navy2, lineHeight: 1.5 }}>
            <b>Voorbeeld:</b><br/>
            "Ik ben Focus Puller op een Nederlandse speelfilm met internationaal crew, 28 draaidagen waarvan 6 nachtopnames. Ik werk zelfstandig met een 1st AC."
          </div>
        </AsideCard>
      </div>

      <div className="step-nav" style={{ marginTop: 32, display: "flex", justifyContent: "space-between" }}>
        <FwButton variant="ghost" arrow={false} onClick={back}>← Terug</FwButton>
      </div>
    </div>
  );
};

const rolCard = (primary) => ({
  background: FW.white, border: `1.5px solid ${primary ? FW.navy : FW.gray100}`,
  borderRadius: 14, padding: 16, textAlign: "left", cursor: "pointer",
  fontFamily: "var(--font-sans)", width: "100%",
  boxShadow: primary ? "0 4px 12px rgba(0,0,0,.08)" : "none",
});

const RolTooltip = ({ tekst }) => {
  const [pos, setPos] = React.useState(null);
  const iconRef = React.useRef(null);
  if (!tekst || !tekst.trim()) return null;
  const toon = (e) => {
    e.stopPropagation();
    if (!iconRef.current) return;
    const r = iconRef.current.getBoundingClientRect();
    const maxW = 280;
    const left = Math.min(r.left, window.innerWidth - maxW - 12);
    setPos({ top: r.bottom + 6, left: Math.max(12, left), maxW });
  };
  const verberg = (e) => { e.stopPropagation(); setPos(null); };
  return (
    <span style={{ display: "inline-flex", alignItems: "center" }}
      onMouseEnter={toon} onMouseLeave={verberg}
      onFocus={toon} onBlur={verberg}
      onClick={(e) => { e.stopPropagation(); e.preventDefault(); pos ? verberg(e) : toon(e); }}>
      <i ref={iconRef} className="ri-information-line"
        tabIndex={0}
        aria-label="Rol-omschrijving"
        style={{
          fontSize: 16, color: FW.gray500, cursor: "help",
          display: "inline-grid", placeItems: "center", outline: "none",
        }} />
      {pos && (
        <span role="tooltip" style={{
          position: "fixed", top: pos.top, left: pos.left, zIndex: 1000,
          width: "max-content", maxWidth: pos.maxW, padding: "10px 12px",
          background: FW.navy, color: FW.white, borderRadius: 10,
          fontSize: 13, fontWeight: 500, lineHeight: 1.4, textAlign: "left",
          boxShadow: "0 6px 20px rgba(0,0,0,.18)", pointerEvents: "none",
          whiteSpace: "normal",
        }}>{tekst}</span>
      )}
    </span>
  );
};
window.RolTooltip = RolTooltip;

const NiveauBadge = ({ niveau }) => (
  <span style={{
    display: "inline-grid", placeItems: "center",
    minWidth: 32, padding: "4px 10px", borderRadius: 8,
    background: FW.navy, color: FW.yellow,
    fontSize: 14, fontWeight: 700,
  }}>{niveau}</span>
);
window.NiveauBadge = NiveauBadge;

const StepHeader = ({ tag, title, sub }) => (
  <div style={{ marginBottom: 28 }}>
    {tag && <div style={{ display: "inline-block", padding: "4px 10px", borderRadius: 6,
      background: FW.navy, color: FW.yellow, fontSize: 12, fontWeight: 700,
      textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 14 }}>{tag}</div>}
    <h2 className="step-h2" style={{ fontSize: 36, fontWeight: 700, lineHeight: 1.15, margin: "0 0 10px", letterSpacing: "-0.01em" }}>{title}</h2>
    {sub && <p className="step-sub" style={{ fontSize: 17, color: FW.navy2, maxWidth: 680, margin: 0, lineHeight: 1.45 }}>{sub}</p>}
  </div>
);
window.StepHeader = StepHeader;

const AsideCard = ({ children }) => (
  <div className="aside-card" style={{ background: "#E7FFF2", borderRadius: 20, padding: 22, position: "sticky", top: 20 }}>
    {children}
  </div>
);
window.AsideCard = AsideCard;

window.StepRol = StepRol;
