/* ================================================
   Views: List, Map, Detail
================================================ */

function ListView({ parcels, onSelect, onNew, layout, setLayout, mapStyle }) {
  const [q, setQ] = React.useState("");
  const [sortFilter, setSortFilter] = React.useState("all");

  const filtered = parcels.filter((p) => {
    const matchQ = !q || p.lagebuch.toLowerCase().includes(q.toLowerCase())
      || p.lage.toLowerCase().includes(q.toLowerCase())
      || p.sorte.toLowerCase().includes(q.toLowerCase());
    const matchS = sortFilter === "all" || p.sorte === sortFilter;
    return matchQ && matchS;
  });

  const totalHa = filtered.reduce((s, p) => s + p.flaeche, 0);
  const sortenCount = new Set(parcels.map((p) => p.sorte)).size;
  const oldest = parcels.reduce((a, p) => p.pflanzjahr < a ? p.pflanzjahr : a, 9999);

  const sortOptions = ["all", ...new Set(parcels.map((p) => p.sorte))];

  return (
    <>
      <div className="kpis">
        <div className="kpi">
          <div className="kpi-label">Flächen gesamt</div>
          <div className="kpi-value">{parcels.length}<span className="kpi-unit"> Parzellen</span></div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Gesamtfläche</div>
          <div className="kpi-value">{fmtNum(parcels.reduce((s, p) => s + p.flaeche, 0))}<span className="kpi-unit"> ha</span></div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Sorten</div>
          <div className="kpi-value">{sortenCount}<span className="kpi-unit"> verschieden</span></div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Älteste Anlage</div>
          <div className="kpi-value">{oldest}<span className="kpi-unit"> · {new Date().getFullYear() - oldest} Jahre</span></div>
        </div>
      </div>

      <div className="toolbar">
        <div className="search">
          <Icon.Search />
          <input placeholder="Flächen, Lagen, Sorten durchsuchen…" value={q} onChange={(e) => setQ(e.target.value)} />
        </div>
        {sortOptions.map((s) => (
          <button key={s} className={`chip ${sortFilter === s ? "active" : ""}`} onClick={() => setSortFilter(s)}>
            {s === "all" ? "Alle Sorten" : s}
          </button>
        ))}
        <div style={{ marginLeft: "auto", fontSize: 12, color: "var(--ink-3)", fontFamily: "var(--font-mono)" }}>
          {filtered.length} Fläche{filtered.length !== 1 ? "n" : ""} · {fmtNum(totalHa)} ha
        </div>
      </div>

      {layout === "table" ? (
        <div className="table-wrap">
          <table className="parcels">
            <thead>
              <tr>
                <th>Lagebuch</th>
                <th>Lage</th>
                <th>Sorte</th>
                <th>Pflanzjahr</th>
                <th style={{ textAlign: "right" }}>Fläche</th>
                <th>Erziehung</th>
                <th>Letzte Bearbeitung</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((p) => (
                <tr key={p.id} onClick={() => onSelect(p)}>
                  <td><span className="mono">{p.lagebuch}</span></td>
                  <td style={{ fontWeight: 500, color: "var(--ink-1)" }}>{p.lage}</td>
                  <td><SortPill sorte={p.sorte} /></td>
                  <td className="mono">{p.pflanzjahr}</td>
                  <td className="mono" style={{ textAlign: "right", fontWeight: 500, color: "var(--ink-1)" }}>{fmtNum(p.flaeche)} ha</td>
                  <td>{p.erziehung}</td>
                  <td className="mono">{fmtDate(p.letzteBearbeitung)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="cards">
          {filtered.map((p) => (
            <div key={p.id} className="card" onClick={() => onSelect(p)}>
              <div className="card-preview">
                <ThumbnailMap parcel={p} mapStyle={mapStyle} />
              </div>
              <div className="card-body">
                <div className="card-lagebuch">{p.lagebuch}</div>
                <div className="card-title">{p.lage}</div>
                <div style={{ marginBottom: 10 }}><SortPill sorte={p.sorte} /></div>
                <div className="card-meta">
                  <span>Pflanzjahr {p.pflanzjahr}</span>
                  <span className="card-area">{fmtNum(p.flaeche)} ha</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </>
  );
}

window.ListView = ListView;

/* ------- Map view ------- */
function MapView({ parcels, onSelect, activeId, setActiveId, mapStyle }) {
  return (
    <div className="map-layout">
      <div className="map-sidebar">
        <div className="map-sidebar-hd">
          <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.12em", color: "var(--ink-3)", fontWeight: 600, marginBottom: 4 }}>
            Parzellen-Register
          </div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 500 }}>
            {parcels.length} Flächen · {fmtNum(parcels.reduce((s, p) => s + p.flaeche, 0))} ha
          </div>
        </div>
        <div className="map-sidebar-list">
          {parcels.map((p) => (
            <div
              key={p.id}
              className={`map-list-item ${activeId === p.id ? "active" : ""}`}
              onClick={() => setActiveId(p.id)}
              onDoubleClick={() => onSelect(p)}
            >
              <div className="map-list-color" style={{ background: p.farbe }} />
              <div className="map-list-body">
                <div className="map-list-title">{p.lage}</div>
                <div className="map-list-meta">
                  <span>{p.lagebuch}</span>
                  <span>·</span>
                  <span>{fmtNum(p.flaeche)} ha</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className="map-canvas">
        <ParcelsMap
          parcels={parcels}
          mapStyle={mapStyle}
          activeId={activeId}
          onSelect={(p) => { setActiveId(p.id); }}
        />
        <div className="map-overlay-panel">
          <div className="map-overlay-title">Legende · Rebsorten</div>
          {Array.from(new Set(parcels.map((p) => p.sorte))).map((s) => {
            const p = parcels.find((x) => x.sorte === s);
            return (
              <div key={s} className="legend-row">
                <span style={{ width: 12, height: 12, borderRadius: 3, background: p.farbe, border: "1px solid rgba(0,0,0,0.2)" }} />
                {s}
              </div>
            );
          })}
        </div>
        <div className="map-scale">48.08°N, 7.65°E · Kaiserstuhl</div>
      </div>
    </div>
  );
}

window.MapView = MapView;

/* ------- Detail view ------- */
function DetailView({ parcel, onBack, onEdit, mapStyle }) {
  const [sideOpen, setSideOpen] = React.useState(false);

  // Sidebar schließen, wenn eine andere Parzelle geöffnet wird.
  React.useEffect(() => {
    setSideOpen(false);
  }, [parcel.id]);

  return (
    <div className={`detail${sideOpen ? " detail--side-open" : ""}`}>
      <div className="detail-main">
        <div className="detail-back" onClick={onBack}>
          <Icon.Back />
          <span>Zurück zur Übersicht</span>
        </div>
        <div className="detail-head">
          <div>
            <div className="detail-lagebuch">{parcel.lagebuch}</div>
            <h1 className="detail-title">{parcel.lage}</h1>
            <div className="detail-sub">
              <SortPill sorte={parcel.sorte} />
              <span style={{ marginLeft: 12 }}>Pflanzjahr {parcel.pflanzjahr}</span>
              <span style={{ marginLeft: 12 }}>· {parcel.erziehung}</span>
            </div>
          </div>
          <div style={{ display: "flex", gap: 8, alignItems: "flex-start" }}>
            <button className="btn btn-secondary" onClick={onEdit}>
              <Icon.Settings style={{ width: 14, height: 14 }} /> Bearbeiten
            </button>
            <button
              className="btn btn-secondary"
              onClick={() => setSideOpen(o => !o)}
              title={sideOpen ? "Details ausblenden" : "Details einblenden"}
            >
              <Icon.List style={{ width: 14, height: 14 }} />
              {sideOpen ? "Details ausblenden" : "Details"}
            </button>
          </div>
        </div>

        <div className="detail-map">
          <SingleParcelMap parcel={parcel} mapStyle={mapStyle} />
        </div>

        <div className="detail-stats" style={{ gridTemplateColumns: "repeat(3, 1fr)" }}>
          <div className="stat">
            <div className="stat-label">Flächeninhalt</div>
            <div className="stat-value">{fmtNum(parcel.flaeche)} ha</div>
          </div>
          <div className="stat">
            <div className="stat-label">Umfang</div>
            <div className="stat-value">~{Math.round(Math.sqrt(parcel.flaeche * 10000) * 4)} m</div>
          </div>
          <div className="stat">
            <div className="stat-label">Alter</div>
            <div className="stat-value">{new Date().getFullYear() - parcel.pflanzjahr} J.</div>
          </div>
        </div>

        <div className="section-title">Notizen</div>
        <div className="notes-box">{parcel.notizen}</div>
      </div>

      {sideOpen && (
        <div className="detail-side">
          <div className="section-title" style={{ marginTop: 0 }}>Historie</div>
          <div className="timeline">
            {parcel.historie.map((h, i) => (
              <div key={i} className="timeline-item">
                <div className="timeline-date">{fmtDate(h.datum)}</div>
                <div className="timeline-text">{h.text}</div>
              </div>
            ))}
          </div>

          <div className="section-title">Stammdaten</div>
          <div className="summary-section" style={{ background: "var(--parchment)" }}>
            <div className="summary-row"><span className="k">Lagebuch-Nr.</span><span className="v">{parcel.lagebuch}</span></div>
            <div className="summary-row"><span className="k">Lage</span><span className="v">{parcel.lage}</span></div>
            <div className="summary-row"><span className="k">Sorte</span><span className="v">{parcel.sorte}</span></div>
            <div className="summary-row"><span className="k">Pflanzjahr</span><span className="v">{parcel.pflanzjahr}</span></div>
            <div className="summary-row"><span className="k">Erziehung</span><span className="v">{parcel.erziehung}</span></div>
            <div className="summary-row"><span className="k">Fläche</span><span className="v">{fmtNum(parcel.flaeche)} ha</span></div>
            <div className="summary-row"><span className="k">Zuletzt geändert</span><span className="v">{fmtDate(parcel.letzteBearbeitung)}</span></div>
          </div>
        </div>
      )}
    </div>
  );
}

window.DetailView = DetailView;
