// 07-land-projekt.jsx — Land search + 5-step Projektierung Wizard
// Step 1: GET /api/properties?property_type=land (live) or ImDataExt.land (fallback)
// Step 2-4: Client-side state
// Step 5: POST /api/projects or localStorage TODO if endpoint missing
window.ImTemplates = window.ImTemplates || {};

window.ImTemplates.Land = function Land() {
  const { useState, useEffect, useCallback } = React;

  // Wizard state
  const [step,    setStep]    = useState(0);
  const steps = ['Plot', 'Program', 'Budget', 'Summary', 'Submit'];

  // Step 1: plot search
  const [plots,      setPlots]      = useState(null);
  const [plotError,  setPlotError]  = useState(null);
  const [searchQ,    setSearchQ]    = useState('');
  const [filterHa,   setFilterHa]   = useState('');
  const [filterZone, setFilterZone] = useState('');
  const [selectedPlot, setSelectedPlot] = useState(null);

  // Step 2: program specs (client-side)
  const [program, setProgram] = useState({
    units: 10, unit_type: 'apartment', amenity_sqm: 200, pool: false, far: 0.3,
  });

  // Step 3: budget calc (client-side, CH-specific values)
  const CH_COSTS = {
    utility_connection: 25000,   // CHF per plot (power + water + sewer typical CH)
    permits_pct:        0.008,   // 0.8% of land price
    contingency_pct:    0.10,    // 10% contingency
    construction_per_sqm: 3200,  // CHF/m² typical CH residential
  };
  const [currency, setCurrency] = useState('CHF');

  // Step 4: project name for submission
  const [projName, setProjName] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [submitMsg, setSubmitMsg] = useState(null);

  // Fetch plots on mount
  useEffect(() => {
    fetchPlots({});
  }, []);

  const fetchPlots = (filters) => {
    setPlotError(null); setPlots(null);
    const params = new URLSearchParams({ property_type: 'land', limit: '20' });
    if (filters.q)    params.set('q', filters.q);
    if (filters.ha)   params.set('land_ha_max', filters.ha);
    if (filters.zone) params.set('zoning', filters.zone);
    window.IM_API.call(`/api/properties?${params}`)
      .then(r => {
        const data = r.data || r.properties || [];
        if (data.length > 0) {
          setPlots(data.map(normalisePlot));
        } else {
          // Fallback to ImDataExt seed
          setPlots(seedPlots());
        }
      })
      .catch(() => setPlots(seedPlots()));
  };

  const normalisePlot = (p) => ({
    id:       p.id || p.uuid,
    area:     p.district || p.address || p.title || '—',
    ha:       p.land_area_sqm ? (p.land_area_sqm / 10000).toFixed(1) : '—',
    zoning:   p.community_type || p.ownership_type || 'W3',
    tenure:   p.title_deed_type === 'freehold' ? 'Freehold' : (p.title_deed_type || 'Freehold'),
    price:    p.price || 0,
    currency: p.currency || p.price_currency || 'CHF',
    envelope: p.description ? p.description.substring(0, 60) : 'Mixed-use development',
    sqm:      p.land_area_sqm || (p.area_sqm || 0),
  });

  const seedPlots = () => {
    const ext = (window.ImDataExt && window.ImDataExt.land) || [];
    if (ext.length > 0) return ext;
    return [
      { id: 'LP-71', area: 'Zug, CH',       ha: '1.4', zoning: 'W3', tenure: 'Freehold', price: 4800000, currency: 'CHF', envelope: 'Mixed-use 4 floors', sqm: 14000 },
      { id: 'LP-72', area: 'Lausanne, CH',   ha: '0.8', zoning: 'W2', tenure: 'Freehold', price: 2100000, currency: 'CHF', envelope: 'Residential 3 floors', sqm: 8000  },
      { id: 'LP-73', area: 'Berlin, DE',     ha: '2.2', zoning: 'M2', tenure: 'Freehold', price: 3400000, currency: 'EUR', envelope: 'Commercial 5 floors', sqm: 22000 },
      { id: 'LP-74', area: 'Vienna, AT',     ha: '1.1', zoning: 'W3', tenure: 'Freehold', price: 2800000, currency: 'EUR', envelope: 'Residential/mixed', sqm: 11000  },
    ];
  };

  // Budget calculation
  const calcBudget = (plot) => {
    if (!plot) return null;
    const land   = plot.price || 0;
    const sellableGfa = (plot.sqm || 10000) * (program.far || 0.3);
    const construction = sellableGfa * CH_COSTS.construction_per_sqm;
    const utilities  = CH_COSTS.utility_connection;
    const permits    = land * CH_COSTS.permits_pct;
    const units_n    = program.units || 10;
    const total_dev  = construction + utilities + permits;
    const contingency = total_dev * CH_COSTS.contingency_pct;
    const total      = land + total_dev + contingency;
    const avg_unit_price = total / units_n;
    const gdv        = avg_unit_price * units_n * 1.35; // 35% margin target
    const irr_est    = ((gdv - total) / total * 100).toFixed(1);
    const margin_pct = ((gdv - total) / gdv * 100).toFixed(1);
    return { land, construction, utilities, permits, contingency, total, gdv, irr_est, margin_pct, sellableGfa: Math.round(sellableGfa), units_n, avg_unit_price };
  };

  const handleSearch = useCallback(() => {
    fetchPlots({ q: searchQ, ha: filterHa, zone: filterZone });
  }, [searchQ, filterHa, filterZone]);

  const handleSubmit = async () => {
    setSubmitting(true); setSubmitMsg(null);
    const payload = {
      name:         projName || (selectedPlot ? `Project ${selectedPlot.area}` : 'New land project'),
      property_id:  selectedPlot ? selectedPlot.id : null,
      land_plot:    selectedPlot,
      program,
      budget:       calcBudget(selectedPlot),
      currency,
    };
    try {
      await window.IM_API.call('/api/projects', { method: 'POST', body: payload });
      setSubmitMsg({ ok: true, text: 'Project saved successfully.' });
    } catch {
      // TODO: /api/projects endpoint not yet mounted — save to localStorage
      try {
        const saved = JSON.parse(localStorage.getItem('ri_projects') || '[]');
        saved.push({ ...payload, id: 'LOCAL-' + Date.now(), created_at: new Date().toISOString() });
        localStorage.setItem('ri_projects', JSON.stringify(saved));
        setSubmitMsg({ ok: true, text: 'Saved locally (server endpoint pending). Reference: ' + payload.name });
      } catch {
        setSubmitMsg({ ok: false, text: 'Save failed.' });
      }
    }
    setSubmitting(false);
  };

  const budget = calcBudget(selectedPlot);
  const fmtM = (v, cur) => (cur || currency) + ' ' + (v / 1e6).toFixed(2) + 'M';

  return (
    <div className="im-page" style={{ padding: 'var(--s-6) var(--s-7)' }}>
      <div className="mono up" style={{ fontSize: 'var(--fs-2xs)', color: 'var(--accent)', letterSpacing: 'var(--tr-mono)' }}>07 · LAND + PROJEKTIERUNG</div>
      <h1 style={{ fontSize: 'var(--fs-4xl)', fontWeight: 500, letterSpacing: 'var(--tr-tight)', margin: '8px 0 var(--s-5)' }}>Plots → envelope → ROI</h1>

      {/* Wizard stepper */}
      <div className="im-wizard" style={{ marginBottom: 'var(--s-6)' }}>
        {steps.map((s, i) => (
          <div
            key={s}
            className={'im-wizard-step ' + (i < step ? 'is-done' : i === step ? 'is-active' : '')}
            onClick={() => i < step && setStep(i)}
            style={{ cursor: i < step ? 'pointer' : 'default' }}>
            <span className="n">{i < step ? '✓' : i + 1}</span>
            <span>{s}</span>
          </div>
        ))}
      </div>

      {/* ── STEP 0: Plot search ── */}
      {step === 0 && (
        <div>
          <div style={{ display: 'flex', gap: 8, marginBottom: 'var(--s-4)' }}>
            <input
              className="im-input"
              style={{ flex: 1 }}
              placeholder="Search by area, zoning, canton…"
              value={searchQ}
              onChange={e => setSearchQ(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && handleSearch()}
            />
            <button className="im-btn is-ghost" aria-label="Filter: Grundstücke über 5 ha" onClick={() => setFilterHa(filterHa === '5' ? '' : '5')}>
              {filterHa ? `≤ ${filterHa} ha ×` : 'Hectares: 1–10'}
            </button>
            <button className="im-btn is-ghost" aria-label="Filter: Wohnzone W3" onClick={() => setFilterZone(filterZone === 'W3' ? '' : 'W3')}>
              {filterZone ? `Zone: ${filterZone} ×` : 'Zoning: any'}
            </button>
            <button className="im-btn is-primary" aria-label="Grundstücke suchen" onClick={handleSearch}>Search</button>
          </div>

          {plots === null && (
            <div className="im-spinner" style={{ margin: '48px auto', display: 'block' }} />
          )}
          {plotError && (
            <div className="im-alert"><div>{plotError}</div></div>
          )}
          {plots && plots.length === 0 && (
            <div style={{ color: 'var(--text-mid)', textAlign: 'center', padding: '48px 0' }}>No land plots found. Try a broader search.</div>
          )}
          {plots && plots.length > 0 && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--s-4)' }}>
              {plots.map(p => (
                <div
                  key={p.id}
                  className="im-land"
                  style={{ outline: selectedPlot && selectedPlot.id === p.id ? '2px solid var(--accent)' : 'none', cursor: 'pointer' }}
                  onClick={() => setSelectedPlot(p)}>
                  <div className="im-land-sat" style={{ position: 'relative' }}>
                    <svg viewBox="0 0 100 60" preserveAspectRatio="none">
                      <polygon points="20,15 75,12 82,40 65,52 25,48 15,30" fill="rgba(167,139,250,.25)" stroke="var(--accent)" strokeWidth=".6" strokeDasharray="2,1.5" />
                    </svg>
                    <span className="im-pill" style={{ position: 'absolute', top: 10, left: 10, background: 'rgba(0,0,0,.55)' }}>● {p.zoning}</span>
                    <span className="im-pill" style={{ position: 'absolute', top: 10, right: 10, background: 'var(--accent)', color: 'var(--text-on-accent)' }}>{p.ha} ha</span>
                  </div>
                  <div className="im-land-body">
                    <div style={{ fontWeight: 600 }}>{p.area}</div>
                    <div className="mono" style={{ fontSize: 'var(--fs-2xs)', color: 'var(--text-lo)' }}>{p.id} · {p.tenure}</div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 'var(--s-3)' }}>
                      <div className="mono" style={{ fontSize: 'var(--fs-lg)', fontWeight: 600, color: 'var(--accent)' }}>
                        {p.currency === 'EUR' ? '€' : 'CHF '}{(p.price / 1e6).toFixed(1)}M
                      </div>
                      <div className="mono" style={{ fontSize: 'var(--fs-2xs)', color: 'var(--text-mid)' }}>{p.envelope}</div>
                    </div>
                    <button
                      className={'im-btn is-sm ' + (selectedPlot && selectedPlot.id === p.id ? 'is-primary' : 'is-ghost')}
                      style={{ width: '100%', marginTop: 'var(--s-3)' }}
                      onClick={() => { setSelectedPlot(p); setStep(1); }}>
                      {selectedPlot && selectedPlot.id === p.id ? 'Selected → Continue' : 'Select this plot →'}
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
          {selectedPlot && (
            <div style={{ marginTop: 24, display: 'flex', justifyContent: 'flex-end' }}>
              <button className="im-btn is-primary" aria-label={`Weiter mit ${selectedPlot.area}`} onClick={() => setStep(1)}>Continue with {selectedPlot.area} →</button>
            </div>
          )}
        </div>
      )}

      {/* ── STEP 1: Program specs ── */}
      {step === 1 && (
        <div style={{ maxWidth: 640 }}>
          {!selectedPlot && (
            <div className="im-alert" style={{ marginBottom: 16 }}>
              <div>No plot selected. <button className="im-btn is-ghost is-sm" aria-label="Zurück zur Grundstückauswahl" onClick={() => setStep(0)}>← Go back and select a plot</button></div>
            </div>
          )}
          <div className="im-card" style={{ padding: 'var(--s-5)' }}>
            <div className="mono up" style={{ fontSize: 'var(--fs-2xs)', color: 'var(--text-lo)', marginBottom: 'var(--s-3)' }}>DEVELOPMENT PROGRAM</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <div className="im-field">
                <label className="im-label">Number of units</label>
                <input className="im-input" aria-label="Mindestfläche in Hektar" type="number" min="1" max="500"
                  value={program.units}
                  onChange={e => setProgram(p => ({ ...p, units: parseInt(e.target.value) || 1 }))} />
              </div>
              <div className="im-field">
                <label className="im-label">Unit type</label>
                <select className="im-select" value={program.unit_type} onChange={e => setProgram(p => ({ ...p, unit_type: e.target.value }))}>
                  <option value="apartment">Apartments</option>
                  <option value="villa">Villas</option>
                  <option value="townhouse">Townhouses</option>
                  <option value="commercial">Commercial</option>
                  <option value="mixed">Mixed-use</option>
                </select>
              </div>
              <div className="im-field">
                <label className="im-label">Amenity area (m²)</label>
                <input className="im-input" aria-label="Mindestpreis" type="number" min="0"                   value={program.amenity_sqm}
                  onChange={e => setProgram(p => ({ ...p, amenity_sqm: parseInt(e.target.value) || 0 }))} />
              </div>
              <div className="im-field">
                <label className="im-label">Floor Area Ratio (FAR)</label>
                <input className="im-input" aria-label="Geschossflächenzahl (GFZ)" type="number" min="0.1" max="3" step="0.05"
                  value={program.far}
                  onChange={e => setProgram(p => ({ ...p, far: parseFloat(e.target.value) || 0.3 }))} />
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div className={'im-toggle ' + (program.pool ? 'is-on' : '')} onClick={() => setProgram(p => ({ ...p, pool: !p.pool }))} />
                <span style={{ fontSize: 'var(--fs-sm)', color: 'var(--text-mid)' }}>Include pool / clubhouse</span>
              </div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 24, justifyContent: 'flex-end' }}>
            <button className="im-btn is-ghost" aria-label="Zurück zu Schritt 1" onClick={() => setStep(0)}>← Back</button>
            <button className="im-btn is-primary" aria-label="Weiter zu Budget-Rechner" onClick={() => setStep(2)}>Calculate budget →</button>
          </div>
        </div>
      )}

      {/* ── STEP 2: Budget calc ── */}
      {step === 2 && (
        <div style={{ maxWidth: 640 }}>
          <div className="im-card" style={{ padding: 'var(--s-5)' }}>
            <div className="mono up" style={{ fontSize: 'var(--fs-2xs)', color: 'var(--text-lo)', marginBottom: 'var(--s-3)' }}>COST BREAKDOWN (CH-STANDARD)</div>
            <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
              <span style={{ fontSize: 'var(--fs-sm)', color: 'var(--text-mid)', alignSelf: 'center' }}>Currency:</span>
              <div className="im-segment">
                {['CHF', 'EUR', 'USD'].map(c => (
                  <button key={c} className={currency === c ? 'is-active' : ''} aria-label={`Währung: ${c}`} onClick={() => setCurrency(c)}>{c}</button>
                ))}
              </div>
            </div>
            {budget ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {[
                  { k: 'Land cost',              v: fmtM(budget.land) },
                  { k: 'Construction',           v: fmtM(budget.construction), hint: `${budget.sellableGfa} m² × ${CH_COSTS.construction_per_sqm.toLocaleString()} CHF/m²` },
                  { k: 'Utility connections',    v: fmtM(budget.utilities), hint: 'Power / water / sewer (CH avg)' },
                  { k: 'Permits & legal',        v: fmtM(budget.permits), hint: '0.8% of land' },
                  { k: 'Contingency (10%)',      v: fmtM(budget.contingency) },
                  { k: 'TOTAL DEVELOPMENT',      v: fmtM(budget.total), bold: true },
                  { k: 'Gross Dev. Value (GDV)', v: fmtM(budget.gdv), ok: true },
                  { k: 'Estimated IRR',          v: budget.irr_est + '%', ok: true },
                  { k: 'Margin',                 v: budget.margin_pct + '%', ok: true },
                ].map(row => (
                  <div key={row.k} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--line)', fontSize: 'var(--fs-sm)' }}>
                    <div>
                      <span style={{ color: row.bold ? 'var(--text-hi)' : 'var(--text-mid)', fontWeight: row.bold ? 600 : 400 }}>{row.k}</span>
                      {row.hint && <div className="mono" style={{ fontSize: 'var(--fs-3xs)', color: 'var(--text-faint)' }}>{row.hint}</div>}
                    </div>
                    <span className="mono" style={{ color: row.ok ? 'var(--ok)' : row.bold ? 'var(--accent)' : 'var(--text-hi)', fontWeight: row.bold ? 600 : 400 }}>{row.v}</span>
                  </div>
                ))}
              </div>
            ) : (
              <div style={{ color: 'var(--text-mid)' }}>Select a plot in Step 1 to calculate costs.</div>
            )}
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 24, justifyContent: 'flex-end' }}>
            <button className="im-btn is-ghost" aria-label="Zurück zu Schritt 2" onClick={() => setStep(1)}>← Back</button>
            <button className="im-btn is-primary" aria-label="Weiter zur Zusammenfassung" onClick={() => setStep(3)}>View summary →</button>
          </div>
        </div>
      )}

      {/* ── STEP 3: Summary card ── */}
      {step === 3 && (
        <div style={{ maxWidth: 640 }}>
          <div className="im-card" style={{ padding: 'var(--s-5)' }}>
            <div className="mono up" style={{ fontSize: 'var(--fs-2xs)', color: 'var(--accent)', marginBottom: 'var(--s-3)' }}>
              AI ENVELOPE · {selectedPlot ? selectedPlot.id : 'NO PLOT'}
            </div>
            <div style={{ fontSize: 'var(--fs-xl)', fontWeight: 600, marginTop: 4 }}>
              {selectedPlot ? `${selectedPlot.area} · ${selectedPlot.ha} ha` : 'No plot selected'}
            </div>
            <div style={{ height: 1, background: 'var(--line)', margin: 'var(--s-4) 0' }} />
            <div className="mono up" style={{ fontSize: 'var(--fs-3xs)', color: 'var(--text-lo)', marginBottom: 8 }}>SUGGESTED PROGRAM</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {[
                { k: `${program.unit_type.charAt(0).toUpperCase() + program.unit_type.slice(1)}s`, v: `${program.units} units` },
                program.amenity_sqm > 0 && { k: 'Amenity building', v: `${program.amenity_sqm} m²` },
                program.pool && { k: 'Pool / clubhouse', v: 'Yes' },
                budget && { k: 'Sellable GFA', v: `${budget.sellableGfa.toLocaleString()} m²` },
                { k: 'FAR', v: program.far },
              ].filter(Boolean).map(x => (
                <div key={x.k} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 'var(--fs-sm)', padding: '4px 0' }}>
                  <span style={{ color: 'var(--text-mid)' }}>{x.k}</span>
                  <span className="mono">{x.v}</span>
                </div>
              ))}
            </div>
            {budget && (
              <>
                <div style={{ height: 1, background: 'var(--line)', margin: 'var(--s-4) 0' }} />
                <div className="mono up" style={{ fontSize: 'var(--fs-3xs)', color: 'var(--text-lo)', marginBottom: 8 }}>ROI</div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                  {[
                    { l: 'GDV',     v: fmtM(budget.gdv) },
                    { l: 'IRR',     v: budget.irr_est + '%', ok: true },
                    { l: 'TOTAL',   v: fmtM(budget.total) },
                    { l: 'MARGIN',  v: budget.margin_pct + '%', ok: true },
                  ].map(kpi => (
                    <div key={kpi.l} className="im-kpi" style={{ padding: 'var(--s-3)' }}>
                      <div className="mono up" style={{ fontSize: 'var(--fs-3xs)', color: 'var(--text-lo)' }}>{kpi.l}</div>
                      <div className="mono" style={{ fontSize: 'var(--fs-lg)', fontWeight: 600, color: kpi.ok ? 'var(--ok)' : 'var(--accent)' }}>{kpi.v}</div>
                    </div>
                  ))}
                </div>
              </>
            )}
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 24, justifyContent: 'flex-end' }}>
            <button className="im-btn is-ghost" aria-label="Zurück zu Schritt 3" onClick={() => setStep(2)}>← Back</button>
            <button className="im-btn is-primary" aria-label="Projekt einreichen" onClick={() => setStep(4)}>Submit project →</button>
          </div>
        </div>
      )}

      {/* ── STEP 4: Submit ── */}
      {step === 4 && (
        <div style={{ maxWidth: 480 }}>
          <div className="im-card" style={{ padding: 'var(--s-5)' }}>
            <div className="mono up" style={{ fontSize: 'var(--fs-2xs)', color: 'var(--text-lo)', marginBottom: 'var(--s-3)' }}>SUBMIT PROJECT</div>
            {submitMsg ? (
              <div className="im-alert" style={{ borderColor: submitMsg.ok ? 'var(--ok)' : 'var(--bad)' }}>
                <div>{submitMsg.text}</div>
              </div>
            ) : (
              <>
                <div className="im-field" style={{ marginBottom: 16 }}>
                  <label className="im-label">Project name</label>
                  <input className="im-input"
                    placeholder={selectedPlot ? `Project ${selectedPlot.area}` : 'My land project'}
                    value={projName}
                    onChange={e => setProjName(e.target.value)} />
                </div>
                {selectedPlot && (
                  <div style={{ fontSize: 'var(--fs-sm)', color: 'var(--text-mid)', marginBottom: 16 }}>
                    Plot: <strong>{selectedPlot.area}</strong> ({selectedPlot.ha} ha) ·
                    {program.units} {program.unit_type}s · FAR {program.far}
                  </div>
                )}
                <div style={{ display: 'flex', gap: 8 }}>
                  <button className="im-btn is-ghost" aria-label="Zurück zu Schritt 4" onClick={() => setStep(3)} disabled={submitting}>← Back</button>
                  <button className="im-btn is-primary" aria-label="Projekt endgültig einreichen" onClick={handleSubmit} disabled={submitting}>
                    {submitting ? 'Saving…' : 'Save project'}
                  </button>
                </div>
              </>
            )}
          </div>
        </div>
      )}
    </div>
  );
};
