/* ============================================================
   Forms — add/edit employee, add company (modals)
   ============================================================ */
const Df = window.PavData;

const DEPTS = ["Inžinerija", "Dizainas", "Rinkodara", "Pardavimai", "Administracija", "Vadovybė", "Konsultacijos", "Analitika", "Apskaita", "Projektai"];
const STATUSES = [
  { value: "aktyvus", label: "Aktyvus" },
  { value: "atostogos", label: "Atostogos" },
  { value: "liga", label: "Liga" },
];

function EmployeeForm({ initial, onSave, onClose, onDelete }) {
  const editing = !!initial;
  const [f, setF] = useState(() => ({
    first: initial?.first || "",
    last: initial?.last || "",
    position: initial?.position || "",
    dept: initial?.dept || "Inžinerija",
    payType: initial?.payType || "monthly", // monthly | hourly
    gross: initial?.gross != null ? String(initial.gross) : "",
    hourlyRate: initial?.hourlyRate != null ? String(initial.hourlyRate) : "",
    hours: initial?.hours != null ? String(initial.hours) : "168",
    overtimeHours: initial?.overtimeHours != null ? String(initial.overtimeHours) : "0",
    nightHours: initial?.nightHours != null ? String(initial.nightHours) : "0",
    hireDate: initial?.hireDate || new Date().toISOString().slice(0, 10),
    status: initial?.status || "aktyvus",
    pillarII: initial?.pillarII || false,
  }));
  const set = (k) => (v) => setF((s) => ({ ...s, [k]: v }));
  const num = (x) => parseFloat(String(x).replace(",", ".")) || 0;
  const hourly = f.payType === "hourly";
  const gross = hourly
    ? Df.variableGross({ hourlyRate: num(f.hourlyRate), hours: num(f.hours), overtimeHours: num(f.overtimeHours), nightHours: num(f.nightHours) })
    : num(f.gross);
  const preview = Df.calcPayroll(gross || 0, { pillarII: f.pillarII });
  const valid = f.first.trim() && f.last.trim() && gross > 0;

  const save = () => {
    if (!valid) return;
    onSave(Df.buildEmployee({ ...initial, ...f, gross, hourlyRate: num(f.hourlyRate), hours: num(f.hours), overtimeHours: num(f.overtimeHours), nightHours: num(f.nightHours) }));
  };

  return (
    <Modal
      title={editing ? "Redaguoti darbuotoją" : "Naujas darbuotojas"}
      onClose={onClose}
      footer={
        <>
          {editing && <span className="danger-link" style={{ marginRight: "auto" }} onClick={onDelete}><Icon name="x" size={14} sw={2.2} /> Pašalinti</span>}
          <button className="btn btn--ghost" style={{ padding: "10px 18px", fontSize: 14 }} onClick={onClose}>Atšaukti</button>
          <button className="btn btn--primary" style={{ padding: "10px 18px", fontSize: 14, opacity: valid ? 1 : .5, pointerEvents: valid ? "auto" : "none" }} onClick={save}>
            <Icon name="check" size={15} sw={2.4} /> {editing ? "Išsaugoti" : "Pridėti"}
          </button>
        </>
      }
    >
      <div className="form-grid">
        <Field label="Vardas" value={f.first} onChange={set("first")} placeholder="Jonas" />
        <Field label="Pavardė" value={f.last} onChange={set("last")} placeholder="Jonaitis" />
        <Field label="Pareigos" value={f.position} onChange={set("position")} placeholder="Programuotojas" span />
        <SelectField label="Padalinys" value={f.dept} onChange={set("dept")} options={DEPTS.map((d) => ({ value: d, label: d }))} />
        <SelectField label="Būsena" value={f.status} onChange={set("status")} options={STATUSES} />
        <SelectField label="Atlygio tipas" value={f.payType} onChange={set("payType")} span options={[{ value: "monthly", label: "Mėnesinis atlyginimas" }, { value: "hourly", label: "Valandinis atlygis" }]} />
        {hourly ? (
          <>
            <Field label="Valandinis tarifas" value={f.hourlyRate} onChange={set("hourlyRate")} inputMode="decimal" placeholder="9.50" suffix="€/val" />
            <Field label="Dirbta valandų" value={f.hours} onChange={set("hours")} inputMode="decimal" suffix="val" />
            <Field label="Viršvalandžiai (×1,5)" value={f.overtimeHours} onChange={set("overtimeHours")} inputMode="decimal" suffix="val" />
            <Field label="Naktinės (+50 %)" value={f.nightHours} onChange={set("nightHours")} inputMode="decimal" suffix="val" />
          </>
        ) : (
          <Field label="Atlyginimas (bruto)" value={f.gross} onChange={set("gross")} inputMode="decimal" placeholder="2000" suffix="€" />
        )}
        <Field label="Įdarbinimo data" value={f.hireDate} onChange={set("hireDate")} type="date" />
        <ToggleField label="Pensijų kaupimas (II pakopa)" hint="Papildomi +3 % Sodros" value={f.pillarII} onChange={set("pillarII")} />
      </div>
      {gross > 0 && (
        <div className="card" style={{ marginTop: 16, boxShadow: "none", background: "var(--bg)" }}>
          <div style={{ padding: "12px 16px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span style={{ fontSize: 12.5, color: "var(--ink-faint)" }}>{hourly ? `Bruto ${Df.fmtEur(gross)} → neto` : "Apskaičiuotas neto atlyginimas"}</span>
            <b style={{ fontFamily: "var(--mono)", fontSize: 17, color: "var(--accent-strong)" }}>{Df.fmtEur(preview.net)}</b>
          </div>
        </div>
      )}
    </Modal>
  );
}

function CompanyForm({ onSave, onClose }) {
  const [f, setF] = useState({ name: "", kind: "", code: "", vat: "", address: "" });
  const set = (k) => (v) => setF((s) => ({ ...s, [k]: v }));
  const valid = f.name.trim().length > 1;
  const save = () => { if (valid) onSave(Df.buildCompany(f)); };
  return (
    <Modal
      title="Pridėti įmonę"
      onClose={onClose}
      footer={
        <>
          <button className="btn btn--ghost" style={{ padding: "10px 18px", fontSize: 14 }} onClick={onClose}>Atšaukti</button>
          <button className="btn btn--primary" style={{ padding: "10px 18px", fontSize: 14, opacity: valid ? 1 : .5, pointerEvents: valid ? "auto" : "none" }} onClick={save}>
            <Icon name="check" size={15} sw={2.4} /> Pridėti įmonę
          </button>
        </>
      }
    >
      <div className="form-grid">
        <Field label="Pavadinimas" value={f.name} onChange={set("name")} placeholder="UAB „Pavyzdys“" span />
        <Field label="Veiklos sritis" value={f.kind} onChange={set("kind")} placeholder="Prekyba" />
        <Field label="Įmonės kodas" value={f.code} onChange={set("code")} placeholder="300000000" />
        <Field label="PVM kodas" value={f.vat} onChange={set("vat")} placeholder="LT100000000000" />
        <Field label="Adresas" value={f.address} onChange={set("address")} placeholder="Gedimino pr. 1, Vilnius" />
      </div>
      <p style={{ fontSize: 12.5, color: "var(--ink-faint)", marginTop: 14 }}>
        Įmonę galėsite papildyti darbuotojais iš karto po sukūrimo.
      </p>
    </Modal>
  );
}

Object.assign(window, { EmployeeForm, CompanyForm, CompanyWizard });

/* ============================================================
   New-company onboarding wizard: company → first employee → done
   ============================================================ */
function CompanyWizard({ onComplete, onClose }) {
  const [step, setStep] = useState(0);
  const [co, setCo] = useState({ name: "", kind: "", code: "", vat: "", address: "" });
  const [emp, setEmp] = useState({ first: "", last: "", position: "", dept: "Administracija", gross: "" });
  const setC = (k) => (v) => setCo((s) => ({ ...s, [k]: v }));
  const setE = (k) => (v) => setEmp((s) => ({ ...s, [k]: v }));
  const num = (x) => parseFloat(String(x).replace(",", ".")) || 0;

  const coValid = co.name.trim().length > 1;
  const empValid = emp.first.trim() && emp.last.trim() && num(emp.gross) > 0;
  const preview = Df.calcPayroll(num(emp.gross) || 0, {});

  const steps = ["Įmonė", "Pirmas darbuotojas", "Baigta"];

  const finish = () => {
    const company = Df.buildCompany(co);
    if (empValid) company.employees = [Df.buildEmployee({ ...emp, gross: num(emp.gross) })];
    onComplete(company);
  };

  return (
    <Modal
      title="Naujos įmonės nustatymas" wide onClose={onClose}
      footer={
        <>
          <div className="wiz-dots" style={{ marginRight: "auto" }}>
            {steps.map((s, i) => <span key={i} className={"wiz-dot" + (i === step ? " on" : "") + (i < step ? " done" : "")}></span>)}
          </div>
          {step > 0 && step < 2 && <button className="btn btn--ghost" style={{ padding: "10px 18px", fontSize: 14 }} onClick={() => setStep(step - 1)}>Atgal</button>}
          {step === 0 && <button className="btn btn--primary" style={{ padding: "10px 18px", fontSize: 14, opacity: coValid ? 1 : .5, pointerEvents: coValid ? "auto" : "none" }} onClick={() => setStep(1)}>Toliau <Icon name="chevRight" size={14} /></button>}
          {step === 1 && <button className="btn btn--primary" style={{ padding: "10px 18px", fontSize: 14 }} onClick={() => setStep(2)}>{empValid ? "Toliau" : "Praleisti"} <Icon name="chevRight" size={14} /></button>}
          {step === 2 && <button className="btn btn--primary" style={{ padding: "10px 18px", fontSize: 14 }} onClick={finish}><Icon name="check" size={15} sw={2.4} /> Sukurti įmonę</button>}
        </>
      }
    >
      <div className="wiz-steps">
        {steps.map((s, i) => (
          <div key={i} className={"wiz-step" + (i === step ? " on" : "") + (i < step ? " done" : "")}>
            <span className="ws-n">{i < step ? <Icon name="check" size={13} sw={3} /> : i + 1}</span>{s}
          </div>
        ))}
      </div>

      {step === 0 && (
        <div className="form-grid" style={{ marginTop: 20 }}>
          <Field label="Pavadinimas" value={co.name} onChange={setC("name")} placeholder="UAB „Pavyzdys“" span />
          <Field label="Veiklos sritis" value={co.kind} onChange={setC("kind")} placeholder="Prekyba" />
          <Field label="Įmonės kodas" value={co.code} onChange={setC("code")} placeholder="300000000" />
          <Field label="PVM kodas" value={co.vat} onChange={setC("vat")} placeholder="LT100000000000" />
          <Field label="Adresas" value={co.address} onChange={setC("address")} placeholder="Gedimino pr. 1, Vilnius" />
        </div>
      )}
      {step === 1 && (
        <div style={{ marginTop: 20 }}>
          <p style={{ fontSize: 13.5, color: "var(--ink-soft)", marginBottom: 16 }}>Pridėkite pirmą darbuotoją (galite praleisti ir tai padaryti vėliau).</p>
          <div className="form-grid">
            <Field label="Vardas" value={emp.first} onChange={setE("first")} placeholder="Jonas" />
            <Field label="Pavardė" value={emp.last} onChange={setE("last")} placeholder="Jonaitis" />
            <Field label="Pareigos" value={emp.position} onChange={setE("position")} placeholder="Vadybininkas" span />
            <SelectField label="Padalinys" value={emp.dept} onChange={setE("dept")} options={DEPTS.map((d) => ({ value: d, label: d }))} />
            <Field label="Atlyginimas (bruto)" value={emp.gross} onChange={setE("gross")} inputMode="decimal" placeholder="2000" suffix="€" />
          </div>
          {num(emp.gross) > 0 && (
            <div className="card" style={{ marginTop: 14, boxShadow: "none", background: "var(--bg)", padding: "12px 16px", display: "flex", justifyContent: "space-between" }}>
              <span style={{ fontSize: 12.5, color: "var(--ink-faint)" }}>Neto atlyginimas</span>
              <b style={{ fontFamily: "var(--mono)", color: "var(--accent-strong)" }}>{Df.fmtEur(preview.net)}</b>
            </div>
          )}
        </div>
      )}
      {step === 2 && (
        <div style={{ marginTop: 20, textAlign: "center", padding: "20px 0" }}>
          <div style={{ width: 64, height: 64, borderRadius: 18, background: "var(--accent-soft)", color: "var(--accent-strong)", display: "grid", placeItems: "center", margin: "0 auto 18px" }}>
            <Icon name="check" size={32} sw={2.4} />
          </div>
          <h3 style={{ fontSize: 20, fontWeight: 650 }}>Viskas paruošta!</h3>
          <p style={{ fontSize: 14, color: "var(--ink-soft)", marginTop: 8, maxWidth: 360, marginInline: "auto", lineHeight: 1.55 }}>
            <b>{co.name || "Įmonė"}</b> bus sukurta{empValid ? ` su darbuotoju ${emp.first} ${emp.last}` : ""}. Galėsite iškart apskaičiuoti darbo užmokestį.
          </p>
        </div>
      )}
    </Modal>
  );
}
