// TextiGreen v4 · result hero

const { useState: useSr4 } = React;

function ResultView({ result, loading, error }) {
  if (error) {
    return <div style={{ padding: 24 }}><WarningBar tone="strong">Estimate failed: {error}. Check connection settings.</WarningBar></div>;
  }
  if (loading && !result) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        <Skeleton height={140} dark />
        <Skeleton height={120} />
        <Skeleton height={90} />
      </div>
    );
  }
  if (!result) return null;

  const r = result;
  const dim = loading ? 0.5 : 1;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 22, opacity: dim, transition: 'opacity 0.15s' }}>

      {/* ─── Headline ─────────────────────────────── */}
      <section style={{ background: 'var(--fg)', color: 'var(--bg)', padding: '28px 24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 10, fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', fontFamily: 'var(--mono)', opacity: 0.65 }}>
          <span>GWP · {r.boundary}</span>
          <span title={`per kg of product at the ${r.boundary} stage`}>{r.unit}</span>
        </div>

        {r.summable && r.total_gwp != null ? (
          <>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 14, marginTop: 10 }}>
              <div style={{ fontFamily: 'var(--display)', fontSize: 84, fontWeight: 600, letterSpacing: '-0.04em', lineHeight: 0.9, color: 'var(--bg)', fontVariantNumeric: 'tabular-nums' }}>
                <span title={`Full precision: ${r.total_gwp.toFixed(3)} ${r.unit}`} style={{ cursor: 'default' }}>
                  ~{r.total_gwp < 10 ? (Math.round(r.total_gwp * 10) / 10).toFixed(1) : Math.round(r.total_gwp)}
                </span>
              </div>
              {r._offline ? <OfflineTag danger label="mock data" /> : <OfflineTag dark label="backend live" />}
            </div>

            {r.gwp_min != null && r.gwp_max != null ? (
              <div style={{ marginTop: 22 }}>
                <div style={{ fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', fontFamily: 'var(--mono)', opacity: 0.55, marginBottom: 10 }}>uncertainty range</div>
                <RangeBar value={r.total_gwp} min={r.gwp_min} max={r.gwp_max} dark />
              </div>
            ) : (
              <div style={{ marginTop: 14, fontSize: 11, color: 'rgba(255,255,255,0.5)', fontStyle: 'italic', lineHeight: 1.5 }}>
                Single-point estimate — uncertainty range not yet available.
              </div>
            )}

            {r.color_interval && (
              <div style={{ marginTop: 24 }}>
                <ReferenceBand colorInterval={r.color_interval} dark />
              </div>
            )}
          </>
        ) : (
          <div style={{ marginTop: 16 }}>
            <div style={{ fontFamily: 'var(--display)', fontSize: 30, fontWeight: 600, lineHeight: 1.15, color: 'var(--bg)' }}>
              Not summable
            </div>
            <div style={{ marginTop: 10, fontSize: 13, color: 'rgba(255,255,255,0.8)', lineHeight: 1.6 }}>
              Components sit on incompatible system boundaries{r.component_boundaries?.length ? ` (${r.component_boundaries.join(' · ')})` : ''}, so a single total would be misleading. See the per-component figures below.
            </div>
          </div>
        )}
      </section>

      {/* ─── Components ───────────────────────────── */}
      <section>
        <Label info="Confidence grade reflects data quality — not a product rating. A = high (official or peer-reviewed primary) · B = good · C = indicative (secondary or estimated) · D = proxy / low-confidence.">Components</Label>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {r.components.map((c, i) => <ComponentCard key={i} c={c} sources={r.sources} />)}
        </div>
      </section>

      {/* ─── Corrections (re-bases) ───────────────── */}
      {(r.grid_correction || r.thermal_correction) && (
        <section>
          <Label hint="re-base, not add-on">Corrections</Label>
          <div style={{ border: '1px solid var(--line)', padding: '6px 16px 16px' }}>
            <CorrectionRow title={`Origin grid · ${r.grid_correction?.origin || '—'} vs ${r.grid_correction?.base_geo || 'base'}`} correction={r.grid_correction} />
            <CorrectionRow title={`Boiler fuel · ${r.thermal_correction?.boiler_fuel || '—'} vs ${r.thermal_correction?.base_fuel || 'coal'}`} correction={r.thermal_correction} />
            <div style={{ marginTop: 12, fontSize: 11, color: 'var(--muted)', lineHeight: 1.55 }}>
              A negative Δ means lower footprint at this origin/fuel than the source study's baseline. Both re-base the energy already embedded above — they are not additional emissions.
            </div>
          </div>
        </section>
      )}

      {/* ─── Dyeing (separate boundary) ───────────── */}
      {r.dyeing && <ProcessCard kind="Dyeing" block={r.dyeing} sources={r.sources} />}

      {/* ─── Fabrication (separate load) ──────────── */}
      {r.fabrication && <FabricationCard block={r.fabrication} sources={r.sources} />}

      {/* ─── Sources ──────────────────────────────── */}
      {r.sources && r.sources.length > 0 && (
        <section>
          <Label hint={`${r.sources.length} cited`}>Sources</Label>
          <div style={{ border: '1px solid var(--line)' }}>
            {r.sources.map((s, i) => (
              <div key={s.source_id} style={{ display: 'flex', gap: 12, padding: '13px 16px', borderTop: i > 0 ? '1px solid var(--line)' : 'none' }}>
                <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--fg)', fontWeight: 600, minWidth: 34 }}>{s.source_id}</span>
                <span style={{ flex: 1, fontSize: 12, color: 'var(--body)', lineHeight: 1.5 }}>{s.citation}</span>
                <ConfidenceBadge value={s.confidence_ceiling} />
              </div>
            ))}
          </div>
        </section>
      )}

      {/* ─── Caveats ──────────────────────────────── */}
      {r.caveats && r.caveats.length > 0 && (
        <section>
          <Label>Caveats</Label>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {r.caveats.map((cv, i) => <WarningBar key={i} tone="caveat">{cv}</WarningBar>)}
          </div>
        </section>
      )}

      {/* ─── Redlines ─────────────────────────────── */}
      {r.redlines && r.redlines.length > 0 && (
        <section>
          <Disclosure title="Method redlines">
            <ul style={{ margin: 0, paddingLeft: 18 }}>
              {r.redlines.map((rl, i) => <li key={i} style={{ marginBottom: 6 }}>{rl}</li>)}
            </ul>
          </Disclosure>
        </section>
      )}
    </div>
  );
}

// ─── Component card ─────────────────────────────────────────────────
function ComponentCard({ c, sources }) {
  // A fiber that could not be resolved at the chosen stage comes back without
  // numeric fields — render a graceful "no data" card instead of crashing.
  if (c.gwp_per_kg == null || c.gwp_contribution == null) {
    return (
      <div style={{ border: '1px solid var(--line)', background: 'var(--surface)', padding: '14px 16px' }}>
        <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--fg)' }}>
          <span style={{ fontFamily: 'var(--mono)', color: 'var(--muted)', marginRight: 8 }}>{Math.round((c.fraction || 0) * 100)}%</span>
          {c.fiber}
        </span>
        <div style={{ marginTop: 8, fontSize: 12, color: 'var(--warn-fg)', lineHeight: 1.5 }}>
          {c.error || 'No data for this fiber at the selected stage. Try a different stage or fiber.'}
        </div>
      </div>
    );
  }
  return (
    <div style={{ border: '1px solid var(--line)', background: 'var(--bg)', padding: '14px 16px' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12, marginBottom: 10 }}>
        <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--fg)' }}>
          <span style={{ fontFamily: 'var(--mono)', color: 'var(--muted)', marginRight: 8 }}>{Math.round(c.fraction * 100)}%</span>
          {c.fiber}
        </span>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 14, color: 'var(--fg)', fontVariantNumeric: 'tabular-nums' }}>
          {c.gwp_contribution.toFixed(3)}
        </span>
      </div>

      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)', marginBottom: 10 }}>
        <span>{c.gwp_per_kg} kg/kg</span>
        {c.gwp_min != null
          ? <span>range {c.gwp_min}–{c.gwp_max}</span>
          : <span style={{ fontStyle: 'italic' }}>single-point · range not available</span>
        }
        {c.geo && <span>· {c.geo}</span>}
      </div>

      <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)', marginBottom: 12, lineHeight: 1.5 }}>{c.boundary}</div>

      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
        <ConfidenceBadge value={c.confidence} />
        <SourceChip id={c.source_id} sources={sources} caveat={c.caveat} />
      </div>

      {/* per-component correction status */}
      <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--line)', display: 'grid', gridTemplateColumns: '1fr', gap: 8 }}>
        <CorrStatus label="Grid" c={c.grid_correction} />
        <CorrStatus label="Thermal" c={c.thermal_correction} />
      </div>
    </div>
  );
}

function CorrStatus({ label, c }) {
  if (!c) return null;
  const applied = c.applied;
  const delta = c.total_delta_per_kg != null ? c.total_delta_per_kg : c.delta_per_kg;
  return (
    <div style={{ display: 'flex', gap: 10, alignItems: 'baseline', fontSize: 11 }}>
      <span style={{ fontFamily: 'var(--mono)', color: 'var(--muted)', minWidth: 54 }}>{label}</span>
      {applied ? (
        <span style={{ fontFamily: 'var(--mono)', color: delta > 0 ? 'var(--warn-fg)' : delta < 0 ? 'var(--accent)' : 'var(--fg)' }}>
          Δ {delta > 0 ? '+' : ''}{(delta || 0).toFixed(3)}
        </span>
      ) : (
        <span style={{ color: 'var(--muted)', fontStyle: 'italic', lineHeight: 1.45 }}>{humanizeReason(c.reason)}</span>
      )}
    </div>
  );
}

// ─── Process (dyeing) card ──────────────────────────────────────────
function ProcessCard({ kind, block, sources }) {
  return (
    <section>
      <Label hint="separate boundary — not added to fiber total">{kind}</Label>
      <div style={{ border: '1px solid var(--fg)', background: 'var(--bg)' }}>
        <div style={{ padding: '16px 18px', borderBottom: '1px solid var(--line)' }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12 }}>
            <span style={{ fontSize: 15, fontWeight: 600, color: 'var(--fg)', fontFamily: 'var(--display)' }}>{block.label || block.process}</span>
            <span style={{ fontFamily: 'var(--display)', fontSize: 34, fontWeight: 600, color: 'var(--fg)', letterSpacing: '-0.03em', fontVariantNumeric: 'tabular-nums' }}>
              {block.gwp.toFixed(2)}
            </span>
          </div>
          {block.gwp_min != null ? (
            <div style={{ marginTop: 12 }}>
              <RangeBar value={block.gwp} min={block.gwp_min} max={block.gwp_max} />
            </div>
          ) : (
            <div style={{ marginTop: 10, fontSize: 11, color: 'var(--muted)', fontStyle: 'italic' }}>
              Single-point estimate — uncertainty range not yet available.
            </div>
          )}
          {block.color_interval && <div style={{ marginTop: 14 }}><ReferenceBand colorInterval={block.color_interval} /></div>}
        </div>

        {/* warnings — surfaced prominently */}
        {(block.toxic_warning || block.boundary_warning) && (
          <div style={{ padding: '12px 18px', display: 'flex', flexDirection: 'column', gap: 8, borderBottom: '1px solid var(--line)' }}>
            {block.toxic_warning && <WarningBar tone="strong"><strong>Toxicity · </strong>{block.toxic_warning}</WarningBar>}
            {block.boundary_warning && <WarningBar tone="warn"><strong>Boundary · </strong>{block.boundary_warning}</WarningBar>}
          </div>
        )}

        <div style={{ padding: '14px 18px', display: 'flex', flexDirection: 'column', gap: 4 }}>
          <CorrectionRow title={`Grid re-base · ${block.grid_correction?.origin || '—'}`} correction={block.grid_correction} />
          <CorrectionRow title={`Thermal re-base · ${block.thermal_correction?.boiler_fuel || '—'}`} correction={block.thermal_correction} />
        </div>

        <div style={{ padding: '12px 18px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap' }}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)' }}>{block.boundary}</span>
          <span style={{ display: 'inline-flex', gap: 8, alignItems: 'center' }}>
            <ConfidenceBadge value={block.confidence} />
            <SourceChip id={block.source_id} sources={sources} caveat={block.caveat} />
          </span>
        </div>
        {block.note && <div style={{ padding: '0 18px 16px', fontSize: 11, color: 'var(--muted)', lineHeight: 1.5 }}>{block.note}</div>}
      </div>
    </section>
  );
}

// ─── Fabrication card ───────────────────────────────────────────────
function FabricationCard({ block, sources }) {
  return (
    <section>
      <Label hint="separate load — not added to fiber total">Fabrication</Label>
      <div style={{ border: '1px solid var(--fg)', background: 'var(--bg)', padding: '16px 18px' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12, marginBottom: 14 }}>
          <span style={{ fontSize: 15, fontWeight: 600, color: 'var(--fg)', fontFamily: 'var(--display)', textTransform: 'capitalize' }}>{block.stage}</span>
          <span style={{ fontFamily: 'var(--display)', fontSize: 30, fontWeight: 600, color: 'var(--fg)', letterSpacing: '-0.03em', fontVariantNumeric: 'tabular-nums' }}>
            {block.electricity_emissions_at_origin.toFixed(3)}
          </span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, fontFamily: 'var(--mono)', fontSize: 12 }}>
          <Stat label="kWh / kg" value={block.electricity_kwh_per_kg} />
          <Stat label="grid EF @ origin" value={block.grid_ef_at_origin} />
          <Stat label="Δ vs base" value={`${block.delta_vs_base > 0 ? '+' : ''}${block.delta_vs_base}`} accent={block.delta_vs_base > 0 ? 'warn' : 'accent'} />
        </div>
        <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap' }}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)' }}>electricity only</span>
          <SourceChip id={block.source_id} sources={sources} caveat={block.caveat} />
        </div>
        {block.note && <div style={{ marginTop: 12, fontSize: 11, color: 'var(--muted)', lineHeight: 1.5 }}>{block.note}</div>}
      </div>
    </section>
  );
}

function Stat({ label, value, accent }) {
  const color = accent === 'warn' ? 'var(--warn-fg)' : accent === 'accent' ? 'var(--accent)' : 'var(--fg)';
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <span style={{ color: 'var(--muted)', fontSize: 10, letterSpacing: '0.06em' }}>{label}</span>
      <span style={{ color, fontSize: 14, fontVariantNumeric: 'tabular-nums' }}>{value}</span>
    </div>
  );
}

window.ResultView = ResultView;
