import { useState } from "react";

const CURRENCIES = ["CHF – Schweizer Franken", "EUR – Euro"];

function Field({ label, required, hint, error, half, children }) {
  return (
    <div style={{ marginBottom: 16, ...(half ? { gridColumn: "span 1" } : {}) }}>
      <label style={{ display: "block", fontSize: 12, fontWeight: 500, color: "#1a1a18", marginBottom: 5 }}>
        {label}{required && <span style={{ color: "#A32D2D", marginLeft: 2 }}>*</span>}
      </label>
      {children}
      {hint && !error && <div style={{ fontSize: 10, color: "#888780", marginTop: 4 }}>{hint}</div>}
      {error && <div style={{ fontSize: 10, color: "#A32D2D", marginTop: 4 }}>⚠ {error}</div>}
    </div>
  );
}

const inputStyle = (hasError) => ({
  width: "100%", boxSizing: "border-box",
  padding: "8px 12px", fontSize: 12,
  border: `1px solid ${hasError ? "#A32D2D" : "#B4B2A9"}`,
  borderRadius: 6, background: "#fff", outline: "none",
});

export default function OB05() {
  const [form, setForm] = useState({
    name: "Tauchschule Zürich GmbH", // vorausgefüllt
    street: "", zip: "", city: "",
    phoneLandline: "", phoneMobile: "",
    contactPerson: "", contactEmail: "",
    currency: "", vatNumber: "",
  });
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);

  const set = (key) => (e) => {
    setForm(f => ({ ...f, [key]: e.target.value }));
    setErrors(er => ({ ...er, [key]: undefined }));
  };

  const validate = () => {
    const e = {};
    if (!form.name.trim())          e.name          = "Schulname ist ein Pflichtfeld";
    if (!form.street.trim())        e.street        = "Strasse ist ein Pflichtfeld";
    if (!form.zip.trim())           e.zip           = "PLZ ist ein Pflichtfeld";
    if (!form.city.trim())          e.city          = "Stadt ist ein Pflichtfeld";
    if (!form.phoneLandline.trim() && !form.phoneMobile.trim())
                                    e.phone         = "Mindestens eine Telefonnummer ist Pflicht";
    if (!form.contactPerson.trim()) e.contactPerson = "Kontaktperson ist ein Pflichtfeld";
    if (!form.contactEmail.trim())  e.contactEmail  = "Kontakt-E-Mail ist ein Pflichtfeld";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.contactEmail))
                                    e.contactEmail  = "Ungültige E-Mail-Adresse";
    if (!form.currency)             e.currency      = "Standard-Währung ist ein Pflichtfeld";
    return e;
  };

  const handleSubmit = () => {
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length === 0) setSubmitted(true);
  };

  // Profil-Vollständigkeit berechnen
  const requiredFields = ["name", "street", "zip", "city", "contactPerson", "contactEmail", "currency"];
  const optionalFields = ["vatNumber"];
  const phoneOk = form.phoneLandline.trim() || form.phoneMobile.trim();
  const filledRequired = requiredFields.filter(k => form[k].trim()).length + (phoneOk ? 1 : 0);
  const totalRequired = requiredFields.length + 1;
  const completenessRequired = Math.round((filledRequired / totalRequired) * 100);
  const allFields = [...requiredFields, ...optionalFields, "phoneLandline", "phoneMobile"];
  const filledAll = allFields.filter(k => form[k].trim()).length;
  const totalAll = allFields.length;
  const completenessAll = Math.round((filledAll / totalAll) * 100);

  if (submitted) {
    return (
      <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 400, borderRadius: 8, overflow: "hidden" }}>
        <div style={{ background: "#1a1a18", padding: "10px 24px", display: "flex", alignItems: "center", justifyContent: "space-between", borderRadius: "8px 8px 0 0" }}>
          <span style={{ fontWeight: 700, color: "#fff", fontSize: 15 }}>DiveLogix360</span>
          <span style={{ fontSize: 11, color: "#888780" }}>Registrierung</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: 350, padding: 24 }}>
          <div style={{ textAlign: "center" }}>
            <div style={{ width: 56, height: 56, borderRadius: "50%", background: "#EAF3DE", display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 24, marginBottom: 16 }}>✓</div>
            <div style={{ fontSize: 18, fontWeight: 500, color: "#1a1a18", marginBottom: 8 }}>Schulprofil gespeichert</div>
            <div style={{ fontSize: 13, color: "#5F5E5A", marginBottom: 24 }}>Registrierung abgeschlossen. Weiter zum Dashboard.</div>
            <button onClick={() => alert("→ OB-06: Dashboard")}
              style={{ padding: "10px 28px", fontSize: 13, fontWeight: 500, background: "#185FA5", border: "none", borderRadius: 6, color: "#fff", cursor: "pointer" }}>
              Zum Dashboard →
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 700, borderRadius: 8, overflow: "hidden" }}>

      {/* NAV */}
      <div style={{ background: "#1a1a18", padding: "10px 24px", display: "flex", alignItems: "center", justifyContent: "space-between", borderRadius: "8px 8px 0 0" }}>
        <span style={{ fontWeight: 700, color: "#fff", fontSize: 15 }}>DiveLogix360</span>
        <span style={{ fontSize: 11, color: "#888780" }}>Registrierung</span>
      </div>

      {/* FORTSCHRITTSLEISTE */}
      <div style={{ background: "#fff", borderBottom: "1px solid #D3D1C7", padding: "12px 24px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 0, maxWidth: 560, margin: "0 auto" }}>
          {[
            { n: "1", label: "Link",     done: true,  active: false },
            { n: "2", label: "Passwort", done: true,  active: false },
            { n: "3", label: "2FA",      done: true,  active: false },
            { n: "4", label: "Codes",    done: true,  active: false },
            { n: "5", label: "Profil",   done: false, active: true  },
          ].map((s, i, arr) => (
            <div key={s.n} style={{ display: "flex", alignItems: "center", flex: i < arr.length - 1 ? 1 : 0 }}>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                <div style={{ width: 28, height: 28, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 600,
                  background: s.done ? "#EAF3DE" : s.active ? "#185FA5" : "#F1EFE8",
                  color: s.done ? "#3B6D11" : s.active ? "#fff" : "#B4B2A9",
                  border: s.active ? "2px solid #185FA5" : "2px solid transparent" }}>
                  {s.done ? "✓" : s.n}
                </div>
                <span style={{ fontSize: 9, color: s.active ? "#185FA5" : s.done ? "#3B6D11" : "#B4B2A9", fontWeight: s.active ? 600 : 400, whiteSpace: "nowrap" }}>{s.label}</span>
              </div>
              {i < arr.length - 1 && (
                <div style={{ flex: 1, height: 2, background: s.done ? "#3B6D11" : "#D3D1C7", margin: "0 6px", marginBottom: 16 }} />
              )}
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: "flex", justifyContent: "center", padding: "24px 24px 16px" }}>
        <div style={{ width: "100%", maxWidth: 560 }}>

          {/* TITEL + VOLLSTÄNDIGKEIT */}
          <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 16 }}>
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
                <h1 style={{ fontSize: 20, fontWeight: 500, color: "#1a1a18", margin: 0 }}>Schulprofil ausfüllen</h1>
                <span style={{ background: "#E6F1FB", color: "#185FA5", fontSize: 11, fontWeight: 500, padding: "2px 8px", borderRadius: 20 }}>OB-05</span>
              </div>
              <p style={{ fontSize: 12, color: "#5F5E5A", margin: 0 }}>Vervollständigen Sie die Angaben zu Ihrer Tauchschule.</p>
            </div>
            {/* Vollständigkeits-Indikator: Pflicht + Gesamt */}
            <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
              <div style={{ textAlign: "center", minWidth: 60 }}>
                <div style={{ fontSize: 18, fontWeight: 700, color: completenessRequired === 100 ? "#3B6D11" : completenessRequired >= 50 ? "#BA7517" : "#A32D2D" }}>{completenessRequired}%</div>
                <div style={{ fontSize: 9, color: "#888780", lineHeight: 1.3 }}>Pflicht­felder</div>
              </div>
              <div style={{ width: 1, height: 32, background: "#D3D1C7" }} />
              <div style={{ textAlign: "center", minWidth: 60 }}>
                <div style={{ fontSize: 18, fontWeight: 700, color: completenessAll === 100 ? "#3B6D11" : completenessAll >= 50 ? "#BA7517" : "#A32D2D" }}>{completenessAll}%</div>
                <div style={{ fontSize: 9, color: "#888780", lineHeight: 1.3 }}>alle Felder</div>
              </div>
            </div>
          </div>

          {/* INFO-BANNER */}
          <div style={{ background: "#E6F1FB", border: "1px solid #B5D4F4", borderRadius: 6, padding: "10px 14px", fontSize: 11, color: "#185FA5", marginBottom: 16 }}>
            ℹ Pflichtfelder (*) müssen ausgefüllt sein, bevor Sie Mitarbeitende einladen können (G6). Optionale Felder können Sie jederzeit unter Einstellungen ergänzen.
          </div>

          {/* FORMULAR CARD */}
          <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 10, padding: "20px 24px", marginBottom: 16 }}>

            {/* ── SCHULANGABEN ── */}
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
              <div style={{ flex: 1, height: 1, background: "#D3D1C7" }} />
              <span style={{ fontSize: 11, color: "#888780", whiteSpace: "nowrap" }}>Schulangaben</span>
              <div style={{ flex: 1, height: 1, background: "#D3D1C7" }} />
            </div>

            <Field label="Schulname" required error={errors.name}
              hint="Vorausgefüllt durch Superadmin – bei Bedarf anpassen">
              <input value={form.name} onChange={set("name")} style={inputStyle(errors.name)} />
            </Field>

            <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 12 }}>
              <Field label="Strasse / Nr." required error={errors.street}>
                <input value={form.street} onChange={set("street")} placeholder="Seestrasse 12" style={inputStyle(errors.street)} />
              </Field>
              <Field label="PLZ" required error={errors.zip}>
                <input value={form.zip} onChange={set("zip")} placeholder="8001" style={inputStyle(errors.zip)} />
              </Field>
            </div>

            <Field label="Stadt" required error={errors.city}>
              <input value={form.city} onChange={set("city")} placeholder="Zürich" style={inputStyle(errors.city)} />
            </Field>

            {/* ── KONTAKT ── */}
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16, marginTop: 8 }}>
              <div style={{ flex: 1, height: 1, background: "#D3D1C7" }} />
              <span style={{ fontSize: 11, color: "#888780", whiteSpace: "nowrap" }}>Kontakt</span>
              <div style={{ flex: 1, height: 1, background: "#D3D1C7" }} />
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <Field label="Telefon Festnetz" error={errors.phone}
                hint="Mind. Festnetz oder Mobil Pflicht">
                <input value={form.phoneLandline} onChange={set("phoneLandline")} placeholder="+41 44 123 45 67" style={inputStyle(errors.phone && !form.phoneLandline)} />
              </Field>
              <Field label="Telefon Mobil" error={!form.phoneLandline ? errors.phone : undefined}
                hint="Mind. Festnetz oder Mobil Pflicht">
                <input value={form.phoneMobile} onChange={set("phoneMobile")} placeholder="+41 79 123 45 67" style={inputStyle(errors.phone && !form.phoneMobile)} />
              </Field>
            </div>

            <Field label="Kontaktperson" required error={errors.contactPerson}
              hint="Name der verantwortlichen Person (z.B. Geschäftsführer/in)">
              <input value={form.contactPerson} onChange={set("contactPerson")} placeholder="Max Muster" style={inputStyle(errors.contactPerson)} />
            </Field>

            <Field label="Kontakt-E-Mail" required error={errors.contactEmail}
              hint="Öffentliche Kontakt-E-Mail der Schule (kann von Login-E-Mail abweichen)">
              <input value={form.contactEmail} onChange={set("contactEmail")} placeholder="info@tauchschule.ch" type="email" style={inputStyle(errors.contactEmail)} />
            </Field>

            {/* ── FINANZEN ── */}
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16, marginTop: 8 }}>
              <div style={{ flex: 1, height: 1, background: "#D3D1C7" }} />
              <span style={{ fontSize: 11, color: "#888780", whiteSpace: "nowrap" }}>Finanzen</span>
              <div style={{ flex: 1, height: 1, background: "#D3D1C7" }} />
            </div>

            <Field label="Standard-Währung" required error={errors.currency}
              hint="Kann nach dem ersten Speichern nur noch durch den Superadmin geändert werden (G9)">
              <select value={form.currency} onChange={set("currency")} style={{ ...inputStyle(errors.currency), background: "#fff" }}>
                <option value="">— bitte wählen —</option>
                {CURRENCIES.map(c => <option key={c}>{c}</option>)}
              </select>
            </Field>

            <Field label="MwSt-Nummer" hint="Optional – je nach Land und Unternehmensform">
              <input value={form.vatNumber} onChange={set("vatNumber")} placeholder="CHE-123.456.789 MWST" style={inputStyle(false)} />
            </Field>

            {/* ── LOGO (V2) ── */}
            <div style={{ background: "#F1EFE8", border: "1px dashed #B4B2A9", borderRadius: 6, padding: "12px 16px", textAlign: "center" }}>
              <div style={{ fontSize: 11, color: "#888780" }}>Logo hochladen</div>
              <div style={{ fontSize: 10, color: "#B4B2A9", marginTop: 4 }}>Verfügbar in V2 – kann später unter Einstellungen ergänzt werden</div>
            </div>

          </div>

          {/* PFLICHTFELD-HINWEIS + BUTTON */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
            <span style={{ fontSize: 11, color: "#888780" }}><span style={{ color: "#A32D2D" }}>*</span> Pflichtfeld</span>
            <span style={{ fontSize: 11, color: "#888780" }}>G9: Währung nach Speichern nur via Superadmin änderbar</span>
          </div>

          <button onClick={handleSubmit}
            style={{ width: "100%", padding: "12px", fontSize: 13, fontWeight: 500, background: "#185FA5", border: "none", borderRadius: 8, color: "#fff", cursor: "pointer" }}>
            Schulprofil speichern & zum Dashboard →
          </button>

          {/* METAINFO */}
          <div style={{ marginTop: 16, padding: "8px 12px", background: "#fff", border: "1px solid #D3D1C7", borderRadius: 6, fontSize: 10, color: "#888780" }}>
            Screen: OB-05  |  UC00 – Tenant-Onboarding  |  Akteur: tenant_admin  |  Folge-Screen: OB-06  |  v0.1 – April 2026
          </div>

        </div>
      </div>
    </div>
  );
}
