// src/ui/steps/step2-niveau.jsx — Bevestig zwaarteniveau met uitleg

const StepNiveau = ({ state, setState, next, back }) => {
  const isFestival = state.type === "festival";
  const tariefrijen = isFestival ? window.TARIEVEN_FESTIVAL_2026 : window.TARIEVEN_FILM_AV_2026;
  const huidigeRol = state.rollen?.[0];

  const [niveau, setNiveau] = React.useState(huidigeRol?.niveau);
  const [aiAdvies, setAiAdvies] = React.useState(null);
  const [loadingAi, setLoadingAi] = React.useState(false);
  const [aiError, setAiError] = React.useState(false);

  React.useEffect(() => {
    if (!huidigeRol) { back(); return; }
    if (!(state.omschrijving && state.omschrijving.length > 10 && !aiAdvies)) return;
    const ctrl = new AbortController();
    setLoadingAi(true);
    window.aiHelp.suggestZwaarte(state.omschrijving, huidigeRol?.rol, isFestival, { signal: ctrl.signal }, huidigeRol?.niveau).then(r => {
      if (ctrl.signal.aborted) return;
      setLoadingAi(false);
      if (r) setAiAdvies(r);
      else setAiError(true);
    });
    return () => ctrl.abort();
  }, []);

  // Sync niveau-keuze direct naar parent state — bewaart selectie bij stap-wisselen
  React.useEffect(() => {
    if (!huidigeRol || niveau === undefined || niveau === huidigeRol.niveau) return;
    setState(s => ({
      ...s,
      rollen: (s.rollen || []).map((r, i) =>
        i === 0 ? {
          ...r, niveau,
          niveau_bron: aiAdvies?.niveau === niveau ? "ai-advies" : "handmatig",
        } : r
      ),
    }));
  }, [niveau]);

  if (!huidigeRol) return null;

  const huidige = tariefrijen.find(t => t.niveau === niveau);
  const isValide = !!huidige;
  const adviesValide = aiAdvies && tariefrijen.some(t => t.niveau === aiAdvies.niveau);

  const bevestig = () => {
    setState(s => ({
      ...s,
      rollen: (s.rollen || []).map((r, i) =>
        i === 0 ? { ...r, niveau, niveau_bron: aiAdvies?.niveau === niveau ? "ai-advies" : (huidigeRol?.niveau === niveau ? "rol-lookup" : "handmatig") } : r
      ),
    }));
    next();
  };

  return (
    <div>
      <StepHeader
        tag="Stap 2 — Zwaarteniveau"
        title="Welk niveau past bij jouw opdracht?"
        sub={isFestival
          ? "De Fair Pay richtlijn voor filmfestivals hanteert 12 schalen (gebaseerd op Cao Toneel & Dans), van operationeel tot strategisch. Jouw rol is voorgesorteerd — je kunt het nog aanpassen."
          : "Het Opdracht Kompas deelt werk in op zwaarte (A t/m K). Elk niveau heeft een eigen minimum starttarief. We hebben alvast een niveau voorgesteld — check of het klopt."}
      />

      <div className="row-2col" style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 24, alignItems: "start" }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 700, color: FW.navy, marginBottom: 12 }}>Je rol: <span style={{ fontWeight: 400 }}>{huidigeRol?.rol}</span> · {huidigeRol?.dep}</div>

          {/* Niveau-schaal visueel */}
          <div style={{ background: FW.white, borderRadius: 20, padding: 20, border: `1.5px solid ${FW.gray100}` }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: FW.navy, marginBottom: 14, display: "flex", justifyContent: "space-between" }}>
              <span>Kies het zwaarteniveau</span>
              <span style={{ color: FW.gray500, fontWeight: 500 }}>{isFestival ? "Schaal 1 → 12" : "Schaal A → K"}</span>
            </div>
            {(() => {
              const ascending = tariefrijen.slice().reverse();
              const tiers = isFestival
                ? [
                    { label: "Operationeel", items: ascending.slice(0, 4) },
                    { label: "Tactisch",     items: ascending.slice(4, 8) },
                    { label: "Strategisch",  items: ascending.slice(8, 12) },
                  ]
                : [
                    { label: "Operationeel", items: ascending.slice(0, 3) },
                    { label: "Tactisch",     items: ascending.slice(3, 7) },
                    { label: "Strategisch",  items: ascending.slice(7, 11) },
                  ];
              return (
                <div className="niveau-tiers" style={{ display: "grid", gridTemplateColumns: isFestival ? "repeat(12,1fr)" : "repeat(11,1fr)", gap: 4 }}>
                  {tiers.map(tier => (
                    <div key={tier.label} className="niveau-tier">
                      <div className="niveau-tier-label">{tier.label}</div>
                      <div className="niveau-tier-buttons">
                        {tier.items.map(r => (
                          <button key={r.niveau}
                            onClick={() => setNiveau(r.niveau)}
                            title={`${r.niveau}: € ${r.tarief_min.toFixed(2)}/u`}
                            style={{
                              background: niveau === r.niveau ? FW.navy : FW.cream,
                              color: niveau === r.niveau ? FW.yellow : FW.navy,
                              border: `1.5px solid ${niveau === r.niveau ? FW.navy : FW.gray100}`,
                              borderRadius: 10, padding: "14px 4px", cursor: "pointer",
                              fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 18,
                              transition: "all .15s",
                            }}>{r.niveau}</button>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              );
            })()}
            <div className="niveau-legend-desktop" style={{ display: "flex", justifyContent: "space-between", marginTop: 10, fontSize: 12, color: FW.gray500 }}>
              <span>Operationeel</span>
              <span>Tactisch</span>
              <span>Strategisch</span>
            </div>
          </div>

          {/* Huidige selectie samenvatting */}
          {isValide ? (
            <div className="fw-card-mobile" style={{ marginTop: 20, padding: 24, background: FW.mint, borderRadius: 20 }}>
              <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 20, flexWrap: "wrap" }}>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 700, textTransform: "uppercase", letterSpacing: 0.5, color: FW.navy, opacity: .75 }}>Niveau {huidige.niveau}</div>
                  <div className="step-h2" style={{ fontSize: 28, fontWeight: 700, color: FW.navy, marginTop: 4 }}>
                    {!isFestival && huidige.domein}
                    {isFestival && huidige.rol_voorbeeld}
                  </div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontSize: 13, fontWeight: 700, textTransform: "uppercase", letterSpacing: 0.5, color: FW.navy, opacity: .75 }}>Minimum starttarief</div>
                  <div className="summary-value" style={{ fontSize: 40, fontWeight: 700, color: FW.navy, lineHeight: 1 }}>
                    € {huidige.tarief_min.toFixed(2)}<span style={{ fontSize: 18, fontWeight: 500 }}>/uur</span>
                  </div>
                  {!isFestival && <div style={{ fontSize: 13, color: FW.navy, opacity: .7, marginTop: 2 }}>Bovenkant: € {huidige.tarief_max.toFixed(2)}/u</div>}
                </div>
              </div>
            </div>
          ) : (
            <div style={{ marginTop: 20, padding: 24, background: FW.beige2, borderRadius: 20, border: `1.5px dashed ${FW.gray500}`, textAlign: "center", color: FW.navy2 }}>
              <i className="ri-arrow-up-line" style={{ fontSize: 22 }} />
              <div style={{ fontSize: 15, marginTop: 6, fontWeight: 600 }}>Kies een niveau in het schema hierboven om door te gaan.</div>
            </div>
          )}

          {/* AI advies */}
          {loadingAi && (
            <div style={{ marginTop: 16, padding: 16, background: FW.beige2, borderRadius: 14, display: "flex", alignItems: "center", gap: 10 }}>
              <i className="ri-sparkling-2-line" style={{ fontSize: 18 }} />
              <span style={{ fontSize: 15, color: FW.navy }}>Even denken over een passend niveau voor jouw opdracht…</span>
            </div>
          )}
          {!loadingAi && aiError && (
            <FwInlineBanner type="warning" onDismiss={() => setAiError(false)} style={{ marginTop: 16 }}>
              <div style={{ fontWeight: 700, marginBottom: 4 }}>AI-niveau-advies mislukt — kies zelf het niveau in het schema hierboven.</div>
              {window.__lastAiError && (
                <div style={{ fontSize: 13, color: FW.navy2, fontFamily: "ui-monospace, monospace" }}>
                  {window.__lastAiError}
                </div>
              )}
            </FwInlineBanner>
          )}
          {aiAdvies && (
            <div style={{ marginTop: 16, padding: 18, background: "#FEF9B3", borderRadius: 14, border: `1.5px solid ${FW.yellow}` }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8, fontSize: 13, fontWeight: 700, textTransform: "uppercase", letterSpacing: 0.5 }}>
                <i className="ri-sparkling-2-line" /> AI-advies op basis van je omschrijving
              </div>
              <div style={{ fontSize: 15, lineHeight: 1.5, color: FW.navy2 }}>
                Voorgesteld niveau: <b>{aiAdvies.niveau}</b> — {aiAdvies.reden}
              </div>
              {aiAdvies.twijfel && (
                <div style={{ marginTop: 10, fontSize: 14, color: FW.navy2, fontStyle: "italic" }}>
                  {aiAdvies.twijfel}
                </div>
              )}
              {!adviesValide && (
                <div style={{ marginTop: 10, fontSize: 13, color: "#8B1F1A", fontStyle: "italic" }}>
                  Het AI-advies is geen geldig enkel niveau ({aiAdvies.niveau}). Kies zelf een niveau in het schema hierboven.
                </div>
              )}
              {adviesValide && niveau !== aiAdvies.niveau && (
                <button onClick={() => setNiveau(aiAdvies.niveau)} style={{
                  marginTop: 12, background: FW.navy, color: FW.yellow, border: 0, borderRadius: 999,
                  padding: "8px 14px", fontWeight: 700, fontSize: 14, cursor: "pointer", fontFamily: "var(--font-sans)",
                }}>Neem voorstel {aiAdvies.niveau} over</button>
              )}
            </div>
          )}
        </div>

        <AsideCard>
          <div style={{ fontSize: 14, fontWeight: 700, color: FW.navy, marginBottom: 10, display: "inline-flex", alignItems: "center", gap: 6 }}>
            <i className="ri-information-line" /> Hoe werkt de schaal?
          </div>
          <div style={{ fontSize: 14, lineHeight: 1.5, color: FW.navy2 }}>
            {isFestival ? (
              <>
                <div style={{ marginBottom: 8 }}><b>5</b> — Strategisch (directie, artistiek leider)</div>
                <div style={{ marginBottom: 8 }}><b>4</b> — Hoofd van een afdeling</div>
                <div style={{ marginBottom: 8 }}><b>3</b> — Coördinerend, producent</div>
                <div style={{ marginBottom: 8 }}><b>2</b> — Uitvoerend met eigen inbreng</div>
                <div><b>1</b> — Operationeel, duidelijke instructies</div>
              </>
            ) : (
              <>
                <div style={{ marginBottom: 8 }}><b>J-K</b> — Strategisch (regisseur, showrunner, DoP)</div>
                <div style={{ marginBottom: 8 }}><b>H-I</b> — Leidt eigen departement (1st AD, editor)</div>
                <div style={{ marginBottom: 8 }}><b>F-G</b> — Zelfstandig vakgebied (Focus Puller, researcher)</div>
                <div style={{ marginBottom: 8 }}><b>D-E</b> — Assisteert, eigen inbreng (2nd AC, kostuum op set)</div>
                <div><b>A-C</b> — Operationeel (runner, naaister)</div>
              </>
            )}
          </div>
        </AsideCard>
      </div>

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

window.StepNiveau = StepNiveau;
