// screens.jsx — Dashboard (market data), Catalogue, ModelPage (specs), Watchlist, Settings

const { useState: useStateScr, useMemo: useMemoScr, useEffect: useEffectScr } = React;

function TopBar({ title, subtitle, right }) {
  return (
    <div className="topbar">
      <div className="topbar-l">
        <h1 className="topbar-title">{title}</h1>
        {subtitle && <div className="topbar-sub">{subtitle}</div>}
      </div>
      <div className="topbar-r">
        {right}
        <button className="ghost-btn"><Icon d={ICONS.globe} size={14} /> EN</button>
        <button className="ghost-btn"><Icon d={ICONS.euro} size={14} /> EUR</button>
        <button className="ghost-btn"><Icon d={ICONS.share} size={14} /> Share</button>
        <button
          className="primary-btn"
          onClick={() => {
            document.body.dataset.printStamp = new Date().toLocaleString('en-GB');
            window.print();
          }}
        >
          <Icon d={ICONS.download} size={14} /> Export
        </button>
      </div>
    </div>
  );
}

function Stat({ label, value, hint }) {
  return (
    <div className="stat">
      <div className="stat-lbl">{label}</div>
      <div className="stat-val">{value}</div>
      {hint && <div className="stat-hint">{hint}</div>}
    </div>
  );
}
function Bar({ label, pct, tone }) {
  return (
    <div className={`bar bar-${tone}`}>
      <div className="bar-row"><span>{label}</span><span className="bar-pct">{pct}%</span></div>
      <div className="bar-track"><div className="bar-fill" style={{ width: `${pct}%` }}></div></div>
    </div>
  );
}

// ─── Filter-based variant picker ─────────────────────────────────────────────
// filter shape: { [axisId]: value | '*' }
function VariantFilterPicker({ model, filter, onChange }) {
  const { visible, overflow } = window.computeAxesFor(model);
  const [showMore, setShowMore] = useStateScr(false);
  const set = (key, value) => onChange({ ...filter, [key]: value });

  const renderRow = (axisId) => {
    const opts = window.axisOptions(model, axisId);
    if (!opts || opts.length <= 1) return null;
    const ignored = filter[axisId] === '*';
    const active = filter[axisId];
    const lbl = window.AXIS_LABELS[axisId] || axisId;
    return (
      <PickRow
        key={axisId}
        lbl={lbl}
        values={opts}
        active={active}
        ignored={ignored}
        onPick={(v) => set(axisId, v)}
        onIgnore={() => set(axisId, ignored ? opts[0] : '*')}
        renderValue={axisId === 'condition'
          ? (id) => `Grade ${id}`
          : undefined}
      />
    );
  };

  const liveOverflow = overflow.filter(id => {
    const opts = window.axisOptions(model, id);
    return opts && opts.length > 1;
  });

  return (
    <div className="vpick">
      {visible.map(renderRow)}
      {liveOverflow.length > 0 && (
        <div className="vpick-more">
          <button className="more-toggle" onClick={() => setShowMore(s => !s)}>
            <span>{showMore ? '−' : '+'}</span>
            More options
            <span className="more-count">{liveOverflow.length}</span>
          </button>
          {showMore && (
            <div className="vpick-more-body">
              {liveOverflow.map(renderRow)}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function PickRow({ lbl, values, active, ignored, onPick, onIgnore, renderValue }) {
  return (
    <div className={`vpick-row ${ignored ? 'is-ignored' : ''}`}>
      <button
        className={`vpick-switch ${ignored ? 'on' : ''}`}
        onClick={onIgnore}
        title={ignored ? `Filter by ${lbl.toLowerCase()} again` : `Aggregate across all ${lbl.toLowerCase()}s`}
        aria-label={ignored ? 'Stop ignoring' : 'Ignore axis'}
        role="switch"
        aria-checked={ignored}
      >
        <span className="vpick-switch-track">
          <span className="vpick-switch-thumb"></span>
        </span>
      </button>
      <span className="vpick-lbl">{lbl}</span>
      <div className="vpick-pills">
        {values.map(v => (
          <button key={v}
            className={`pill-btn ${active === v && !ignored ? 'on' : ''} ${ignored ? 'dim' : ''}`}
            onClick={() => onPick(v)}
            disabled={ignored}>
            {renderValue ? renderValue(v) : v}
          </button>
        ))}
      </div>
    </div>
  );
}

// ─── Aggregation helpers ─────────────────────────────────────────────────────
function matchVariants(model, filter) {
  return window.matchVariantsBy(model, filter);
}

function aggregate(matched, filter, model) {
  // Total seller pool watching this model = max across all model variants.
  const allModelVariants = model ? VARIANTS.filter(v => v.modelId === model.id) : matched;
  const totalSellers = allModelVariants.length
    ? Math.max(...allModelVariants.map(v => v.sellers))
    : 0;
  if (matched.length === 0) return null;
  if (matched.length === 1) {
    const v = matched[0];
    return { ...v, label: filterLabel(filter, v), aggregated: false, count: 1, totalSellers };
  }
  // aggregate
  const len = matched[0].series.monthly.length;
  const avg = (arrName) => Array.from({length: matched[0].series[arrName].length}, (_, i) =>
    Math.round(matched.reduce((s, v) => s + v.series[arrName][i], 0) / matched.length));
  const monthly = avg('monthly');
  const weekly = avg('weekly');
  const daily = avg('daily');
  const all = matched.flatMap(v => v.series.weekly);
  const sorted = [...all].sort((a, b) => a - b);
  return {
    id: 'agg',
    aggregated: true,
    count: matched.length,
    label: filterLabel(filter, matched[0]),
    series: { monthly, weekly, daily },
    stats: {
      median:  sorted[Math.floor(sorted.length / 2)],
      highest: sorted[sorted.length - 1],
      lowest:  sorted[0],
      trend:   ((monthly[monthly.length - 1] - monthly[0]) / monthly[0]) * 100,
    },
    availability: Math.round(matched.reduce((s, v) => s + v.availability, 0) / matched.length),
    sellers:      Math.round(matched.reduce((s, v) => s + v.sellers, 0) / matched.length),
    searchTrend:  Math.round(matched.reduce((s, v) => s + v.searchTrend, 0) / matched.length),
    listings:     matched.reduce((s, v) => s + v.listings, 0),
    totalSellers,
    grades: {
      'A+': Math.round(matched.reduce((s, v) => s + ((v.grades && v.grades['A+']) || 0), 0) / matched.length),
      A:   Math.round(matched.reduce((s, v) => s + ((v.grades && v.grades.A)   || 0), 0) / matched.length),
      B:   Math.round(matched.reduce((s, v) => s + ((v.grades && v.grades.B)   || 0), 0) / matched.length),
      C:   Math.round(matched.reduce((s, v) => s + ((v.grades && v.grades.C)   || 0), 0) / matched.length),
    },
  };
}

function filterLabel(filter, sample) {
  const parts = [];
  if (filter.storage) parts.push(filter.storage === '*' ? 'all storage' : filter.storage);
  if (filter.color)   parts.push(filter.color   === '*' ? 'all colors'  : filter.color);
  if (filter.condition) {
    if (filter.condition === '*') parts.push('all conditions');
    else parts.push(`Grade ${filter.condition}`);
  }
  return parts.join(' · ');
}

function defaultFilter(model) {
  return window.defaultFilterForModel(model);
}

// ─── Dashboard ───────────────────────────────────────────────────────────────
function Dashboard({ go, route, watchlist, toggleWatch }) {
  const initialModelId = route.modelId || 'iphone-15';
  const initialModel = MODELS_BY_ID[initialModelId];
  const initialFilter = route.filter
    || (route.variantId ? variantToFilter(VARIANT_BY_ID[route.variantId]) : defaultFilter(initialModel));

  const [modelId, setModelId] = useStateScr(initialModelId);
  const [filter, setFilter] = useStateScr(initialFilter);
  const [range, setRange] = useStateScr('monthly');
  const [period, setPeriod] = useStateScr('Month');
  const [query, setQuery] = useStateScr('');

  useEffectScr(() => {
    if (route.modelId && route.modelId !== modelId) {
      setModelId(route.modelId);
      setFilter(route.filter
        || (route.variantId ? variantToFilter(VARIANT_BY_ID[route.variantId]) : defaultFilter(MODELS_BY_ID[route.modelId])));
    }
  }, [route.modelId, route.variantId]);

  const model = MODELS_BY_ID[modelId];
  const matched = matchVariants(model, filter);
  const view = aggregate(matched, filter, model);
  const series = view ? (view.series[range] || view.series.monthly) : [];
  const variantId = matched.length === 1 ? matched[0].id : null;
  const inWatch = variantId && watchlist.includes(variantId);

  // Shared y-axis across ALL variants of this model so sibling charts/sparklines align
  const modelYDomain = useMemoScr(() => {
    const all = model.variants.flatMap(v => v.series[range] || v.series.monthly);
    if (!all.length) return [0, 100];
    const lo = Math.floor(Math.min(...all) / 100) * 100;
    const hi = Math.ceil(Math.max(...all) / 100) * 100;
    return [lo, hi];
  }, [model.id, range]);

  const matches = useMemoScr(() => {
    if (!query.trim()) return [];
    const q = query.toLowerCase();
    return MODELS.filter(m => m.name.toLowerCase().includes(q) || m.brand.toLowerCase().includes(q)).slice(0, 6);
  }, [query]);

  function changeModel(newModel) {
    setModelId(newModel.id);
    setFilter(defaultFilter(newModel));
    setQuery('');
  }

  return (
    <div className="screen">
      <TopBar title="Dashboard" subtitle="Refurbished electronics market index" />

      <section className="card searchcard">
        <div className="search">
          <Icon d={ICONS.search} size={16} />
          <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search a product to track …" />
          {query && <button className="link" onClick={() => setQuery('')}>clear</button>}
        </div>
        {matches.length > 0 && (
          <div className="search-results">
            {matches.map(m => (
              <button key={m.id} className="search-result" onClick={() => changeModel(m)}>
                <ProductGlyph product={m} size={32} tone="cream" />
                <div className="search-result-text">
                  <strong>{m.name}</strong>
                  <span>{m.brand} · {m.released} · {m.variants.length} variants</span>
                </div>
                <span className="search-result-price">from {fmtPrice(Math.min(...m.variants.map(v => v.stats.lowest)))}</span>
              </button>
            ))}
          </div>
        )}
      </section>

      <section className="card tracked-card">
        <div className="tracked-head">
          <div className="tracked-vis">
            <ProductGlyph product={model} size={92} tone="warm" />
          </div>
          <div className="tracked-meta">
            <div className="eyebrow">Tracked product · {model.brand}</div>
            <h2 className="h2">{model.name}</h2>
            <div className="tracked-sub">
              <span>{model.released}</span><span className="dot-sep">·</span>
              <span>{view ? view.count : 0} variant{view && view.count === 1 ? '' : 's'} match</span><span className="dot-sep">·</span>
              <button className="link" onClick={() => go({ view: 'model', modelId: model.id })}>View full specs →</button>
            </div>
          </div>
          <button
            className={`bookmark inline ${inWatch ? 'on' : ''}`}
            onClick={() => variantId && toggleWatch(variantId)}
            disabled={!variantId}
            title={!variantId ? 'Pick a single variant to bookmark' : ''}
          >
            {inWatch
              ? <><svg width="14" height="14" viewBox="0 0 24 24"><path d="M6 4h12v17l-6-4-6 4z" fill="currentColor"/></svg> Watching</>
              : <><Icon d={ICONS.bookmark} size={14} /> Watch</>}
          </button>
        </div>
        <VariantFilterPicker model={model} filter={filter} onChange={setFilter} />
      </section>

      <section className="card chartcard">
        <div className="card-head">
          <div>
            <div className="eyebrow">Price history</div>
            <h3 className="h3">Median across sellers <span className="h2-sub">· {view ? view.label : '—'}</span></h3>
          </div>
          <div className="range-toggle">
            {['daily','weekly','monthly'].map(r => (
              <button key={r} className={range === r ? 'on' : ''} onClick={() => setRange(r)}>
                {r === 'daily' ? '30d' : r === 'weekly' ? 'Weekly' : 'Monthly'}
              </button>
            ))}
            <select className="year-sel"><option>2026</option><option>2025</option><option>2024</option></select>
          </div>
        </div>
        {view ? <PriceChart series={series} range={range} yDomain={modelYDomain} /> : <div className="empty-inline">No variants match this filter.</div>}
        {view && (
          <div className="chart-foot">
            <div><span className="dot"></span> Median listing price{view.aggregated ? ` · averaged over ${view.count} variants` : ''}</div>
            <div className="muted">Across {view.sellers} sellers · {view.listings.toLocaleString()} listings observed</div>
          </div>
        )}
      </section>

      {view && (
        <>
          <section className="card">
            <div className="card-head">
              <div>
                <div className="eyebrow">Price index</div>
                <h3 className="h3">Summary</h3>
              </div>
              <div className="seg">
                {['Today','Week','Month','Year','Overall'].map((s) => (
                  <button key={s} className={period === s ? 'on' : ''} onClick={() => setPeriod(s)}>{s}</button>
                ))}
              </div>
            </div>
            <div className="stat-grid">
              <Stat label="Median"  value={fmtPrice(view.stats.median)} />
              <Stat label="Highest" value={fmtPrice(view.stats.highest)} />
              <Stat label="Lowest"  value={fmtPrice(view.stats.lowest)} />
              <Stat label="Trend"   value={<Trend value={view.stats.trend} />} />
            </div>
          </section>

          <section className="card">
            <h4 className="h4">Availability</h4>
            <div className="availability-row">
              <div className="big-stat">
                <span className="big-num-val">{view.availability}%</span>
                <div className="muted">today</div>
              </div>
              <div className="availability-detail">
                <div className="availability-fact">
                  <span className="num"><strong>{Math.min(view.sellers, view.totalSellers)}</strong> of {view.totalSellers}</span>
                  <span className="muted small">sellers offer this variant today</span>
                </div>
                <div className="availability-fact">
                  <span className="num"><strong>{view.listings.toLocaleString()}</strong></span>
                  <span className="muted small">active listings · last 30d</span>
                </div>
              </div>
            </div>
          </section>

          <section className="grid-2">
            <div className="card">
              <h4 className="h4">Condition mix</h4>
              <div className="bars">
                <Bar label="Grade A+ — premium new" pct={view.grades['A+'] || 0} tone="aplus" />
                <Bar label="Grade A — like new"    pct={view.grades.A     || 0} tone="a" />
                <Bar label="Grade B — good"        pct={view.grades.B     || 0} tone="b" />
                <Bar label="Grade C — fair"        pct={view.grades.C     || 0} tone="c" />
              </div>
              <div className="muted small">
                {filter.condition === '*' ? 'Aggregated share across all conditions.' : `Within ${(window.CONDITIONS).find(c=>c.id===filter.condition).label} listings.`}
              </div>
            </div>
            <div className="card">
              <h4 className="h4">Demand signal</h4>
              <div className="big-stat">
                <Trend value={view.searchTrend} />
                <div className="muted">vs previous 30 days</div>
              </div>
              <Sparkline data={view.series.daily} w={260} h={48} fluid />
              <div className="muted small">Search-volume index from public listings.</div>
            </div>
          </section>

          {/* "Compare matching variants" section archived → archive/dashboard-compare-variants.jsx (2026-05-08) */}
        </>
      )}
    </div>
  );
}

function variantToFilter(v) {
  return v ? { storage: v.storage, color: v.color, condition: v.condition } : null;
}

// ─── Catalogue ───────────────────────────────────────────────────────────────
function Catalogue({ go, addToOffer, draftCount }) {
  const [query, setQuery] = useStateScr('');
  const [brand, setBrand] = useStateScr('all');
  const brands = ['all', ...Array.from(new Set(MODELS.map(m => m.brand)))];

  const filtered = useMemoScr(() => {
    let xs = MODELS;
    if (query) {
      const q = query.toLowerCase();
      xs = xs.filter(m => m.name.toLowerCase().includes(q) || m.brand.toLowerCase().includes(q) || (m.tagline || '').toLowerCase().includes(q));
    }
    if (brand !== 'all') xs = xs.filter(m => m.brand === brand);
    return xs;
  }, [query, brand]);

  const sections = CATEGORIES.map(c => ({
    ...c, items: filtered.filter(m => m.cat === c.id),
  })).filter(s => s.items.length > 0);

  return (
    <div className="screen">
      <TopBar title="Catalogue" subtitle={`${MODELS.length} models · ${VARIANTS.length} tracked variants across ${CATEGORIES.length} categories`} />

      <section className="card filterbar">
        <div className="search search-inline">
          <Icon d={ICONS.search} size={16} />
          <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search the catalogue …" />
        </div>
        <div className="filter-pills">
          <span className="filter-lbl"><Icon d={ICONS.filter} size={14} /> Brand</span>
          {brands.map(b => (
            <button key={b} className={`pill-btn ${brand === b ? 'on' : ''}`} onClick={() => setBrand(b)}>
              {b === 'all' ? 'All' : b}
            </button>
          ))}
        </div>
      </section>

      {sections.map((s) => (
        <CategorySection key={s.id} section={s} go={go} addToOffer={addToOffer} />
      ))}

      {sections.length === 0 && <div className="empty">No models match your filters.</div>}
    </div>
  );
}

function CategorySection({ section, go, addToOffer }) {
  const [collapsed, setCollapsed] = useStateScr(false);
  return (
    <section className={`cat-section ${collapsed ? 'is-collapsed' : ''}`}>
      <header className="cat-head">
        <button className="cat-head-toggle" onClick={() => setCollapsed(c => !c)} aria-expanded={!collapsed}>
          <span className={`chev ${collapsed ? 'is-closed' : ''}`}><Icon d={ICONS.chevron} size={14} /></span>
          <div className="cat-num">{section.id.slice(0, 2).toUpperCase()}</div>
          <h2 className="cat-title">{section.label}</h2>
        </button>
        <div className="cat-meta">
          <span>{section.items.length} models</span><span className="dot-sep">·</span>
          <span>{section.items.reduce((s, m) => s + m.variants.length, 0)} variants</span>
        </div>
      </header>

      {!collapsed && (
        <div className="prod-grid">
          {section.items.map(m => <ModelCard key={m.id} m={m} go={go} addToOffer={addToOffer} />)}
        </div>
      )}
    </section>
  );
}

function ModelCard({ m, go, addToOffer }) {
  return (
    <div className="prod">
      <button className="prod-img-wrap" onClick={() => go({ view: 'model', modelId: m.id })}>
        <ProductGlyph product={m} size={140} tone="cream" />
        <span className="prod-tag">{m.variants.length} variants</span>
      </button>
      <div className="prod-body">
        <div className="prod-brand">{m.brand} · {m.released}</div>
        <button className="prod-name link-btn" onClick={() => go({ view: 'model', modelId: m.id })}>{m.name}</button>
        <div className="prod-tagline">{m.tagline}</div>
        <div className="prod-foot">
          <span className="prod-meta">{m.storages.length} storage · {m.colors.length} color{m.colors.length === 1 ? '' : 's'}</span>
          {addToOffer
            ? <button className="prod-add" onClick={(e) => { e.stopPropagation(); addToOffer(m.id); }}>
                <Icon d={ICONS.plus} size={12} /> Add to offer
              </button>
            : <Icon d={ICONS.arrow} size={14} />}
        </div>
      </div>
    </div>
  );
}

// ─── Model page ──────────────────────────────────────────────────────────────
function ModelPage({ id, go, watchlist, toggleWatch, addToOffer }) {
  const model = MODELS_BY_ID[id] || MODELS[0];
  const [filter, setFilter] = useStateScr(defaultFilter(model));
  const matched = matchVariants(model, filter);
  const single = matched.length === 1 ? matched[0] : null;
  const inWatch = single && watchlist.includes(single.id);

  return (
    <div className="screen">
      <TopBar
        title={model.name}
        subtitle={
          <span>
            <button className="crumb" onClick={() => go({ view: 'catalogue' })}>Catalogue</button>
            {' / '}<span>{model.brand}</span>{' / '}<span>{model.name}</span>
          </span>
        }
        right={
          <button className={`bookmark inline ${inWatch ? 'on' : ''}`}
                  onClick={() => single && toggleWatch(single.id)}
                  disabled={!single}>
            {inWatch
              ? <><svg width="14" height="14" viewBox="0 0 24 24"><path d="M6 4h12v17l-6-4-6 4z" fill="currentColor"/></svg> Watching</>
              : <><Icon d={ICONS.bookmark} size={14} /> Watch</>}
          </button>
        }
      />

      <section className="hero">
        <div className="hero-visual">
          <ProductGlyph product={model} size={260} tone="warm" />
          <div className="hero-thumbs">
            <ProductGlyph product={model} size={64} tone="cream" />
            <ProductGlyph product={model} size={64} tone="cream" />
            <ProductGlyph product={model} size={64} tone="warm" />
          </div>
        </div>
        <div className="hero-meta">
          <div className="eyebrow">{model.brand} · Released {model.released}</div>
          <h2 className="hero-title">{model.name}</h2>
          <p className="hero-lede">{model.tagline}</p>

          <div className="model-pick">
            <div className="model-pick-head">
              <span className="eyebrow">Pick a variant</span>
              <span className="muted small">{model.variants.length} variants tracked</span>
            </div>
            <VariantFilterPicker model={model} filter={filter} onChange={setFilter} />
            <div className="model-pick-actions">
              <div className="model-pick-summary">
                <span className="muted small">{matched.length === 1 ? 'Selected' : `${matched.length} variants match`}</span>
                <strong>{filterLabel(filter)}</strong>
              </div>
              <button className="primary-btn lg"
                      onClick={() => go({ view: 'dashboard', modelId: model.id, filter })}>
                Open in dashboard <Icon d={ICONS.arrow} size={14} />
              </button>
              {addToOffer && matched.length === 1 && (
                <button className="ghost-btn" onClick={() => { addToOffer(matched[0].id, { lock: true }); go({ view: 'offer-create' }); }}>
                  <Icon d={ICONS.plus} size={14} /> Add to offer
                </button>
              )}
            </div>
          </div>
        </div>
      </section>

      <section className="card">
        <div className="card-head">
          <div>
            <div className="eyebrow">Technical specifications</div>
            <h3 className="h3">Full specs</h3>
          </div>
          <span className="muted small">As released by {model.brand}</span>
        </div>
        <div className="specs-grid">
          {Object.entries(model.specs).map(([k, v]) => (
            <div key={k} className="spec-cell"><dt>{k}</dt><dd>{v}</dd></div>
          ))}
        </div>
      </section>

      <section className="grid-2">
        <div className="card">
          <h4 className="h4">Available colors</h4>
          <div className="color-grid">
            {model.colors.map(c => (
              <div key={c} className="color-cell">
                <span className="color-swatch" data-color={c.toLowerCase()}></span>
                <span>{c}</span>
              </div>
            ))}
          </div>
        </div>
        <div className="card">
          <h4 className="h4">Storage options</h4>
          <div className="storage-grid">
            {model.storages.map(s => <div key={s} className="storage-cell">{s}</div>)}
          </div>
          <div className="muted small" style={{marginTop: 12}}>
            {model.variants.length} total variant combinations (storage × color × condition).
          </div>
        </div>
      </section>

      <section>
        <header className="cat-head">
          <div>
            <div className="cat-num">↗</div>
            <h2 className="cat-title">Related models</h2>
          </div>
          <button className="link" onClick={() => go({ view: 'catalogue' })}>View catalogue →</button>
        </header>
        <div className="prod-grid">
          {MODELS.filter(m => m.cat === model.cat && m.id !== model.id).slice(0, 4).map(m => (
            <ModelCard key={m.id} m={m} go={go} />
          ))}
        </div>
      </section>
    </div>
  );
}

// ─── Watchlist ───────────────────────────────────────────────────────────────
function Watchlist({ go, watchlist, toggleWatch }) {
  const items = watchlist.map(id => VARIANT_BY_ID[id]).filter(Boolean);
  return (
    <div className="screen">
      <TopBar title="Watchlist" subtitle={`${items.length} variant${items.length === 1 ? '' : 's'} saved`} />
      {items.length === 0 ? (
        <div className="empty">
          <div className="empty-glyph">☆</div>
          <h3>Nothing saved yet</h3>
          <p>Bookmark a variant from the dashboard to track it here.</p>
          <button className="primary-btn" onClick={() => go({ view: 'catalogue' })}>Browse catalogue</button>
        </div>
      ) : (
        <div className="watch-table card">
          <div className="watch-head">
            <span>Variant</span><span>Median</span><span>Range</span><span>12-mo trend</span><span>Demand</span><span>Trend</span><span></span>
          </div>
          {items.map(v => {
            const m = MODELS_BY_ID[v.modelId];
            return (
              <div className="watch-row" key={v.id}>
                <button className="watch-prod" onClick={() => go({ view: 'dashboard', modelId: m.id, filter: variantToFilter(v) })}>
                  <ProductGlyph product={m} size={48} tone="cream" />
                  <div>
                    <div className="prod-name">{m.name}</div>
                    <div className="prod-brand">{v.label}</div>
                  </div>
                </button>
                <span className="num">{fmtPrice(v.stats.median)}</span>
                <span className="num muted">{fmtPrice(v.stats.lowest)}–{fmtPrice(v.stats.highest)}</span>
                <span><Trend value={v.stats.trend} /></span>
                <span><Trend value={v.searchTrend} /></span>
                <Sparkline data={v.series.monthly} w={120} h={28} />
                <button className="link" onClick={() => toggleWatch(v.id)}>remove</button>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ─── Settings ────────────────────────────────────────────────────────────────
function Settings() {
  const [currency, setCurrency] = useStateScr('EUR');
  const [region, setRegion] = useStateScr('EU');
  const [notif, setNotif] = useStateScr({ daily: true, weekly: true, alerts: false });
  const u = window.CURRENT_USER || { display_name: 'Unknown', email: '—', role: 'analyst' };
  const initials = (u.display_name || u.email || '?').split(/\s+/).map(s => s[0]).filter(Boolean).slice(0, 2).join('').toUpperCase();
  return (
    <div className="screen">
      <TopBar title="Settings" subtitle="Account and preferences" />
      <section className="grid-2">
        <div className="card">
          <h3 className="h3">Account</h3>
          <div className="acct">
            <div className="avatar">{initials}</div>
            <div>
              <div className="acct-name">{u.display_name}</div>
              <div className="muted">{u.email} · {u.role === 'admin' ? 'Admin' : 'Analyst'}</div>
            </div>
          </div>
          <div className="rule"></div>
          <div className="form">
            <label>Display name<input defaultValue={u.display_name} /></label>
            <label>Email<input defaultValue={u.email} /></label>
            <label>Organization<input defaultValue="reuseit Research GmbH" /></label>
          </div>
          <div className="rule"></div>
          <button
            className="ghost-btn"
            onClick={() => { if (window.logoutCurrentUser) window.logoutCurrentUser(); }}
          >
            <Icon d={ICONS.logout || 'M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9'} size={14} /> Sign out
          </button>
        </div>
        <div className="card">
          <h3 className="h3">Preferences</h3>
          <div className="form">
            <label>Currency
              <select value={currency} onChange={(e) => setCurrency(e.target.value)}>
                <option>EUR</option><option>USD</option><option>GBP</option><option>CHF</option>
              </select>
            </label>
            <label>Region
              <select value={region} onChange={(e) => setRegion(e.target.value)}>
                <option>EU</option><option>DACH</option><option>UK</option><option>US</option>
              </select>
            </label>
          </div>
          <div className="rule"></div>
          <h4 className="h4">Notifications</h4>
          <div className="toggles">
            <Toggle label="Daily index digest" value={notif.daily} onChange={(v) => setNotif({ ...notif, daily: v })} />
            <Toggle label="Weekly market report" value={notif.weekly} onChange={(v) => setNotif({ ...notif, weekly: v })} />
            <Toggle label="Watchlist price alerts" value={notif.alerts} onChange={(v) => setNotif({ ...notif, alerts: v })} />
          </div>
        </div>
      </section>
    </div>
  );
}

function Toggle({ label, value, onChange }) {
  return (
    <label className={`toggle ${value ? 'on' : ''}`}>
      <span>{label}</span>
      <button type="button" onClick={() => onChange(!value)} className="tg-track">
        <span className="tg-thumb"></span>
      </button>
    </label>
  );
}

Object.assign(window, { Dashboard, Catalogue, ModelPage, Watchlist, Settings });
