/* ESG Metrics explorer — Strix observation data table */

const useStrix = () => {
  const [ready, setReady] = React.useState(window.STRIX_READY);
  React.useEffect(() => {
    if (window.STRIX_READY) { setReady(true); return; }
    const handler = () => setReady(true);
    window.addEventListener('strix-loaded', handler);
    return () => window.removeEventListener('strix-loaded', handler);
  }, []);
  return ready;
};
window.useStrix = useStrix;

const ESGExplore = ({ embedded, initialCompany, setRoute }) => {
  const ready = useStrix();
  const [company, setCompany] = React.useState(initialCompany ? strixForCompany(initialCompany) : 'All');
  const [family, setFamily] = React.useState('All');
  const [year, setYear] = React.useState('All');
  const [dimType, setDimType] = React.useState('All');
  const [q, setQ] = React.useState('');
  const [sort, setSort] = React.useState({ k: 'year', dir: 'desc' });

  if (!ready) {
    return (
      <div style={{ padding: 80, textAlign: 'center', color: 'var(--ink-3)', fontFamily: 'var(--mono)', fontSize: 13 }}>
        Loading ESG data…
      </div>
    );
  }

  const obs = window.STRIX_OBSERVATIONS;
  const allYears = [...new Set(obs.map(o => o.report_year))].sort((a, b) => b - a);
  const allFamilies = window.STRIX_FAMILIES;
  const allCompanies = window.STRIX_OBSERVATIONS
    ? [...new Set(obs.map(o => o.company_id))].sort()
    : [];

  const allDimTypes = window.STRIX_DIM_TYPES || [];

  let rows = obs;
  if (company !== 'All') rows = rows.filter(r => r.company_id === company);
  if (family !== 'All') rows = rows.filter(r => r.family === family);
  if (year !== 'All') rows = rows.filter(r => r.report_year === Number(year));
  if (dimType !== 'All') rows = rows.filter(r => r.dimension_type === dimType);
  if (q) {
    const lq = q.toLowerCase();
    rows = rows.filter(r =>
      strixMetricName(r.metric_id).toLowerCase().includes(lq) ||
      strixCompanyName(r.company_id).toLowerCase().includes(lq) ||
      r.unit.toLowerCase().includes(lq)
    );
  }

  rows = [...rows].sort((a, b) => {
    const dir = sort.dir === 'asc' ? 1 : -1;
    if (sort.k === 'year') return (a.report_year - b.report_year) * dir;
    if (sort.k === 'company') return strixCompanyName(a.company_id).localeCompare(strixCompanyName(b.company_id)) * dir;
    if (sort.k === 'metric') return strixMetricName(a.metric_id).localeCompare(strixMetricName(b.metric_id)) * dir;
    if (sort.k === 'value') return ((a.value || 0) - (b.value || 0)) * dir;
    if (sort.k === 'conf') return (a.confidence - b.confidence) * dir;
    return 0;
  });

  const toggleSort = (k) => setSort(s => s.k === k ? { k, dir: s.dir === 'asc' ? 'desc' : 'asc' } : { k, dir: 'desc' });
  const anyFilter = company !== 'All' || family !== 'All' || year !== 'All' || dimType !== 'All' || q;

  const selectStyle = {
    padding: '6px 10px', border: '1px solid var(--line)', borderRadius: 999,
    background: 'var(--canvas)', fontSize: 12, fontFamily: 'var(--mono)',
    color: 'var(--ink-2)', cursor: 'pointer', appearance: 'none',
    WebkitAppearance: 'none', paddingRight: 26,
    backgroundImage: `url("data:image/svg+xml,%3Csvg width='10' height='6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0l5 6 5-6z' fill='%238A8A80'/%3E%3C/svg%3E")`,
    backgroundRepeat: 'no-repeat', backgroundPosition: 'right 10px center',
  };

  return (
    <div>
      {/* Filters */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap', marginBottom: 20 }}>
        <GooeyInput value={q} onValueChange={setQ} placeholder="Search metrics" expandedWidth={240} />
        {!initialCompany && (
          <select value={company} onChange={e => setCompany(e.target.value)} style={selectStyle}>
            <option value="All">All companies</option>
            {allCompanies.map(c => <option key={c} value={c}>{strixCompanyName(c)}</option>)}
          </select>
        )}
        <select value={family} onChange={e => setFamily(e.target.value)} style={selectStyle}>
          <option value="All">All families</option>
          {allFamilies.map(f => <option key={f.id} value={f.id}>{f.name}</option>)}
        </select>
        <select value={year} onChange={e => setYear(e.target.value)} style={selectStyle}>
          <option value="All">All years</option>
          {allYears.map(y => <option key={y} value={y}>{y}</option>)}
        </select>
        <select value={dimType} onChange={e => setDimType(e.target.value)} style={selectStyle}>
          <option value="All">All dimensions</option>
          {allDimTypes.map(dt => <option key={dt} value={dt}>{formatDimType(dt)}</option>)}
        </select>
        {anyFilter && (
          <button onClick={() => { setCompany(initialCompany ? strixForCompany(initialCompany) : 'All'); setFamily('All'); setYear('All'); setDimType('All'); setQ(''); }}
            style={{ background: 'none', border: 'none', fontSize: 12, color: 'var(--ink-3)', cursor: 'pointer', fontFamily: 'var(--mono)' }}>
            Clear
          </button>
        )}
        <div style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--ink-3)', fontFamily: 'var(--mono)' }}>
          {rows.length} of {obs.length}
        </div>
      </div>

      {/* Table */}
      <div style={{ border: '1px solid var(--line)', borderRadius: 12, background: 'var(--canvas)', overflow: 'hidden' }}>
        {/* Header */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: initialCompany ? '1fr 80px 1fr 100px 110px 110px' : '140px 1fr 80px 1fr 100px 110px 110px',
          padding: '10px 20px', background: 'var(--canvas-2)', borderBottom: '1px solid var(--line)', alignItems: 'center',
        }}>
          {!initialCompany && <SortHeader label="COMPANY" k="company" sort={sort} toggle={toggleSort} />}
          <SortHeader label="METRIC" k="metric" sort={sort} toggle={toggleSort} />
          <SortHeader label="YEAR" k="year" sort={sort} toggle={toggleSort} />
          <SortHeader label="VALUE" k="value" sort={sort} toggle={toggleSort} />
          <div className="eyebrow" style={{ fontSize: 11 }}>UNIT</div>
          <div className="eyebrow" style={{ fontSize: 11 }}>BASIS</div>
          <SortHeader label="CONFIDENCE" k="conf" sort={sort} toggle={toggleSort} />
        </div>

        {/* Rows */}
        {rows.length === 0 && (
          <div style={{ padding: 48, textAlign: 'center', color: 'var(--ink-3)', fontSize: 14 }}>
            No ESG metrics match these filters.
          </div>
        )}
        {rows.slice(0, 200).map((r, i) => (
          <div key={`${r.company_id}-${r.metric_id}-${r.report_year}-${i}`} style={{
            display: 'grid',
            gridTemplateColumns: initialCompany ? '1fr 80px 1fr 100px 110px 110px' : '140px 1fr 80px 1fr 100px 110px 110px',
            padding: '14px 20px', borderBottom: '1px solid var(--line)', alignItems: 'center',
          }}>
            {!initialCompany && (
              <div style={{ fontWeight: 600, fontSize: 14 }}>
                {strixCompanyName(r.company_id)}
              </div>
            )}
            <div>
              <div style={{ fontSize: 14, fontWeight: 500 }}>{strixMetricName(r.metric_id)}</div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--mono)', marginTop: 2 }}>
                {strixFamilyName(r.family)}
              </div>
            </div>
            <div style={{ fontFamily: 'var(--mono)', fontSize: 13, color: 'var(--ink-2)' }}>{r.report_year}</div>
            <div>
              <div style={{ fontWeight: 600, fontSize: 14, fontFamily: 'var(--mono)' }}>{formatValue(r.value)}</div>
              {r.value_original != null && (
                <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>
                  {r.value_original} {r.unit_original}
                </div>
              )}
            </div>
            <div style={{ fontSize: 12, color: 'var(--ink-2)', fontFamily: 'var(--mono)' }}>{r.unit}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{formatBasis(r.basis)}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <MiniBar value={r.confidence * 100} tone="var(--moss)" />
              <span style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--ink-2)', minWidth: 24, textAlign: 'right' }}>
                {Math.round(r.confidence * 100)}
              </span>
            </div>
          </div>
        ))}
        {rows.length > 200 && (
          <div style={{ padding: '12px 20px', textAlign: 'center', fontSize: 12, color: 'var(--ink-3)', fontFamily: 'var(--mono)' }}>
            Showing 200 of {rows.length} results. Use filters to narrow.
          </div>
        )}
      </div>
    </div>
  );
};

const SortHeader = ({ label, k, sort, toggle }) => (
  <button onClick={() => toggle(k)} style={{
    background: 'none', border: 'none', cursor: 'pointer', padding: 0, display: 'flex', alignItems: 'center', gap: 4,
  }}>
    <span className="eyebrow" style={{ fontSize: 11, color: sort.k === k ? 'var(--ink)' : 'var(--ink-3)' }}>{label}</span>
    {sort.k === k && (
      <Icon name="chevron-down" size={10} style={{ transform: sort.dir === 'asc' ? 'rotate(180deg)' : 'none', transition: 'transform 160ms' }} />
    )}
  </button>
);

window.ESGExplore = ESGExplore;
window.SortHeader = SortHeader;
