/* ================================================
   Settings — manage Sorten, default map style + list layout
================================================ */

function SettingsView({
  sorten, setSorten,
  mapStyle, setMapStyle,
  listLayout, setListLayout,
  persistTweak,
}) {
  const [editing, setEditing] = React.useState(null); // {index, name, farbe} | "new"
  const [draft, setDraft] = React.useState({ name: "", farbe: "#6B1F2E" });

  function openNew() {
    setDraft({ name: "", farbe: "#6B1F2E" });
    setEditing("new");
  }
  function openEdit(i) {
    setDraft({ name: sorten[i].name, farbe: sorten[i].farbe });
    setEditing(i);
  }
  function closeEditor() { setEditing(null); }

  function saveDraft() {
    const name = draft.name.trim();
    if (!name) return;
    if (editing === "new") {
      if (sorten.some(s => s.name.toLowerCase() === name.toLowerCase())) return;
      setSorten([...sorten, { name, farbe: draft.farbe }]);
    } else {
      const next = sorten.slice();
      next[editing] = { ...next[editing], name, farbe: draft.farbe };
      setSorten(next);
    }
    setEditing(null);
  }

  function removeSorte(i) {
    if (!confirm(`Sorte „${sorten[i].name}“ wirklich löschen?`)) return;
    const next = sorten.slice();
    next.splice(i, 1);
    setSorten(next);
  }

  return (
    <div className="settings">
      <div className="settings-intro">
        <div className="settings-kicker">Administration</div>
        <h2 className="settings-title">Einstellungen</h2>
        <p className="settings-lede">
          Stammdaten für Rebsorten sowie die Standardvorgaben für Karten- und
          Listendarstellung dieses Betriebs.
        </p>
      </div>

      <section className="settings-card">
        <header className="settings-card-head">
          <div>
            <h3>Rebsorten</h3>
            <p>Sorten, die im Wizard und als Legende verwendet werden. Die Farbe färbt Polygone, Punkte und Badges.</p>
          </div>
          <button className="btn btn-primary" onClick={openNew}>
            <Icon.Plus /> Neue Sorte
          </button>
        </header>

        <div className="sorten-grid">
          {sorten.map((s, i) => (
            <div key={s.name + i} className="sorte-card">
              <div className="sorte-swatch" style={{ background: s.farbe }} />
              <div className="sorte-body">
                <div className="sorte-name">{s.name}</div>
                <div className="sorte-hex">{s.farbe.toUpperCase()}</div>
              </div>
              <div className="sorte-actions">
                <button className="icon-btn" onClick={() => openEdit(i)} title="Bearbeiten">
                  <Icon.Sliders />
                </button>
                <button className="icon-btn" onClick={() => removeSorte(i)} title="Löschen">
                  <Icon.Trash />
                </button>
              </div>
            </div>
          ))}
          {sorten.length === 0 && (
            <div className="sorten-empty">Noch keine Sorten angelegt.</div>
          )}
        </div>
      </section>

      <section className="settings-card">
        <header className="settings-card-head">
          <div>
            <h3>Standard-Darstellung</h3>
            <p>Voreinstellungen beim Öffnen der Kartenansicht und der Flächenliste.</p>
          </div>
        </header>

        <div className="settings-rows">
          <div className="settings-row">
            <div>
              <div className="settings-row-title">Kartenstil</div>
              <div className="settings-row-sub">Kachel-Material, das bei jeder Karte geladen wird.</div>
            </div>
            <div className="segmented" style={{ padding: 2 }}>
              <button
                className={mapStyle === "satellite" ? "active" : ""}
                onClick={() => { setMapStyle("satellite"); persistTweak("mapStyle", "satellite"); }}
              >
                Satellit
              </button>
              <button
                className={mapStyle === "illustrated" ? "active" : ""}
                onClick={() => { setMapStyle("illustrated"); persistTweak("mapStyle", "illustrated"); }}
              >
                Illustriert
              </button>
            </div>
          </div>

          <div className="settings-row">
            <div>
              <div className="settings-row-title">Listen-Layout</div>
              <div className="settings-row-sub">Tabellen- oder Kachel­darstellung der Flächenübersicht.</div>
            </div>
            <div className="segmented" style={{ padding: 2 }}>
              <button
                className={listLayout === "table" ? "active" : ""}
                onClick={() => { setListLayout("table"); persistTweak("listLayout", "table"); }}
              >
                <Icon.List /> Tabelle
              </button>
              <button
                className={listLayout === "cards" ? "active" : ""}
                onClick={() => { setListLayout("cards"); persistTweak("listLayout", "cards"); }}
              >
                <Icon.Grid /> Kacheln
              </button>
            </div>
          </div>
        </div>
      </section>

      {editing !== null && (
        <SorteEditor
          draft={draft}
          setDraft={setDraft}
          isNew={editing === "new"}
          onCancel={closeEditor}
          onSave={saveDraft}
        />
      )}
    </div>
  );
}

const SORTE_PRESETS = [
  ["#6B1F2E", "Burgund tief"],
  ["#8B2F42", "Kirsche"],
  ["#A8445B", "Rosé dunkel"],
  ["#C47B5A", "Kupfer"],
  ["#D99A6C", "Terrakotta"],
  ["#8B6F47", "Eiche"],
  ["#B58556", "Karamell"],
  ["#C9A961", "Gold"],
  ["#D4B76A", "Honig"],
  ["#E8DCC4", "Sand"],
  ["#D4C896", "Stroh"],
  ["#B5C47A", "Blattgrün"],
  ["#8EA564", "Weinlaub"],
  ["#6A8548", "Moos"],
  ["#3F4B3A", "Tann"],
];

function SorteEditor({ draft, setDraft, isNew, onCancel, onSave }) {
  const valid = draft.name.trim().length > 0;
  return (
    <div className="modal-backdrop" onClick={(e) => e.target === e.currentTarget && onCancel()}>
      <div
        className="modal sorte-editor-modal"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="modal-head">
          <div>
            <div className="sorte-editor-title">
              {isNew ? "Neue Sorte anlegen" : "Sorte bearbeiten"}
            </div>
            <div className="sorte-editor-sub">
              Diese Farbe erscheint als Polygon-Füllung auf der Karte, als Punkt in Listen und als Legenden-Marker.
            </div>
          </div>
          <button className="modal-close" onClick={onCancel}><Icon.X /></button>
        </div>

        <div className="sorte-editor-body">
          {/* Live preview */}
          <div className="sorte-editor-preview">
            <div className="sorte-editor-preview-label">Vorschau</div>
            <div className="sorte-editor-preview-pill">
              <span className="sort-dot" style={{ background: draft.farbe }} />
              <span>{draft.name.trim() || "Sortenname"}</span>
            </div>
            <div
              className="sorte-editor-preview-tile"
              style={{ background: draft.farbe }}
            >
              <span>{draft.farbe.toUpperCase()}</span>
            </div>
          </div>

          {/* Form */}
          <div className="sorte-editor-form">
            <div className="se-field">
              <label>Name der Sorte</label>
              <input
                type="text"
                value={draft.name}
                onChange={(e) => setDraft({ ...draft, name: e.target.value })}
                placeholder="z. B. Spätburgunder"
                autoFocus
              />
            </div>

            <div className="se-field">
              <label>Farbe</label>
              <div className="se-color-row">
                <label className="se-color-input">
                  <input
                    type="color"
                    value={draft.farbe}
                    onChange={(e) => setDraft({ ...draft, farbe: e.target.value })}
                  />
                  <span className="se-color-input-label">Picker</span>
                </label>
                <div className="se-hex-input">
                  <span className="se-hex-prefix">#</span>
                  <input
                    type="text"
                    value={draft.farbe.replace("#", "").toUpperCase()}
                    onChange={(e) => {
                      const v = e.target.value.replace(/[^0-9a-fA-F]/g, "").slice(0, 6);
                      setDraft({ ...draft, farbe: "#" + v.padEnd(6, "0") });
                    }}
                    maxLength={6}
                  />
                </div>
              </div>

              <div className="se-presets-label">Voreinstellungen</div>
              <div className="se-presets">
                {SORTE_PRESETS.map(([hex, name]) => (
                  <button
                    key={hex}
                    type="button"
                    className={`se-preset ${draft.farbe.toLowerCase() === hex.toLowerCase() ? "selected" : ""}`}
                    onClick={() => setDraft({ ...draft, farbe: hex })}
                    title={`${name} · ${hex}`}
                  >
                    <span className="se-preset-swatch" style={{ background: hex }} />
                    <span className="se-preset-name">{name}</span>
                  </button>
                ))}
              </div>
            </div>
          </div>
        </div>

        <div className="modal-foot">
          <div className="foot-spacer" />
          <button className="btn btn-ghost" onClick={onCancel}>Abbrechen</button>
          <button
            className="btn btn-primary"
            onClick={onSave}
            disabled={!valid}
          >
            <Icon.Check /> {isNew ? "Sorte anlegen" : "Änderungen speichern"}
          </button>
        </div>
      </div>
    </div>
  );
}

window.SettingsView = SettingsView;
