// rating-form.jsx — Mobile-optimized version of the "Deine Meinung" rating form.
// Original desktop is a wide table with criteria rows × ++/+/?/−/−− columns.
// Mobile reflow: each criterion is a row with a 5-segment selector underneath the label.
// Sections are collapsible accordions; users can skip what they're unsure about.

function RatingForm({ dark }) {
  const t = useTheme(dark);

  // Each criterion's `v` is 0..4 mapping to [++, +, ?, −, −−], or null = unanswered
  const sections = [
    {
      id: 'general', label: 'General', open: false,
      criteria: [
        { id: 'g1', label: 'Worthwhile investment > 10% / year', v: 0 },
        { id: 'g2', label: 'Market leader or top 3', v: 1 },
        { id: 'g3', label: 'Future-proof business model', v: 0 },
        { id: 'g4', label: 'Strong brand', v: null },
      ],
    },
    {
      id: 'financials', label: 'Financials', open: true,
      criteria: [
        { id: 'f1', label: 'Revenue growth', v: 1 },
        { id: 'f2', label: 'EBIT growth', v: 1 },
        { id: 'f3', label: 'EBIT margin', v: 2 },
        { id: 'f4', label: 'Valuation', v: 3 },
        { id: 'f5', label: 'Dividend yield', v: 2 },
        { id: 'f6', label: 'Cash flow', v: null },
        { id: 'f7', label: 'Credit rating', v: 0 },
        { id: 'f8', label: 'Growth investments', v: 0 },
        { id: 'f9', label: 'Balance sheet risks', v: null },
      ],
    },
    { id: 'business', label: 'Business model', open: false,
      criteria: [
        { id: 'b1', label: 'Pricing power', v: null },
        { id: 'b2', label: 'Moat / network effects', v: null },
        { id: 'b3', label: 'Recurring revenue', v: null },
      ]},
    { id: 'sustain', label: 'Sustainability', open: false,
      criteria: [
        { id: 's1', label: 'Sustainability matters', v: 3 },
        { id: 's2', label: 'Governance quality', v: null },
      ]},
    { id: 'risk', label: 'Risk factors', open: false,
      criteria: [
        { id: 'r1', label: 'Regulatory exposure', v: null },
        { id: 'r2', label: 'Concentration risk', v: null },
      ]},
  ];

  // Totals for progress strip
  let answered = 0, total = 0;
  sections.forEach(s => { (s.criteria || []).forEach(c => { total++; if (c.v != null) answered++; }); });

  return (
    <div style={{ background: t.bg, color: t.text, height: '100%', display: 'flex', flexDirection: 'column',
      fontFamily: SW_FONT, position: 'relative' }}>

      {/* Header */}
      <div style={{ padding: '54px 16px 8px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ width: 36, height: 36, borderRadius: 18, display: 'flex',
          alignItems: 'center', justifyContent: 'center', fontSize: 20, fontWeight: 500, color: t.text }}>×</div>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
          <div style={{ fontSize: 14, fontWeight: 700, letterSpacing: '-0.01em' }}>Rate AMZN</div>
          <div style={{ fontSize: 11, color: t.textDim, fontFamily: SW_MONO, letterSpacing: '0.01em' }}>
            What speaks for or against · next 2–3 years
          </div>
        </div>
        <div style={{ fontSize: 13, fontWeight: 600, color: t.textMuted }}>Skip</div>
      </div>

      <div style={{ flex: 1, overflow: 'auto', paddingBottom: 100 }}>
        {/* Progress strip */}
        <div style={{ padding: '6px 16px 14px' }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 8 }}>
            <span style={{ fontSize: 12, fontWeight: 600, color: t.textMuted }}>
              <span style={{ fontFamily: SW_MONO, color: t.text, fontWeight: 700 }}>{answered}</span>
              <span> of </span>
              <span style={{ fontFamily: SW_MONO }}>{total}</span>
              <span> answered</span>
            </span>
            <span style={{ fontSize: 11, color: t.textDim }}>Skip any you're unsure about</span>
          </div>
          <div style={{ display: 'flex', gap: 3 }}>
            {Array.from({ length: total }).map((_, i) => (
              <div key={i} style={{
                flex: 1, height: 4, borderRadius: 2,
                background: i < answered ? t.up : t.chip,
              }} />
            ))}
          </div>
        </div>

        {/* Legend (the 5 grades) */}
        <div style={{ padding: '0 16px 14px' }}>
          <div style={{ display: 'flex', gap: 4, padding: '8px 10px', borderRadius: 10,
            background: t.surface, border: `0.5px solid ${t.border}` }}>
            {[
              { label: '++', sub: 'Strong pro', fg: t.up, bg: t.upSoft },
              { label: '+',  sub: 'Pro',         fg: t.up, bg: t.upSoft },
              { label: '?',  sub: 'Unsure',      fg: t.textMuted, bg: t.chip },
              { label: '−',  sub: 'Con',         fg: t.down, bg: t.downSoft },
              { label: '−−', sub: 'Strong con',  fg: t.down, bg: t.downSoft },
            ].map((g, i) => (
              <div key={i} style={{
                flex: 1, padding: '4px 0', textAlign: 'center',
                borderRadius: 6, background: g.bg, color: g.fg,
              }}>
                <div style={{ fontFamily: SW_MONO, fontSize: 11, fontWeight: 700 }}>{g.label}</div>
                <div style={{ fontSize: 9, fontWeight: 600, opacity: 0.8, letterSpacing: '0.02em', marginTop: 1 }}>{g.sub}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Sections */}
        <div style={{ padding: '0 12px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {sections.map(s => <RatingSection key={s.id} t={t} section={s} />)}
        </div>
      </div>

      {/* Sticky save bar */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        padding: '14px 16px 38px',
        background: t.bg,
        borderTop: `0.5px solid ${t.border}`,
      }}>
        <div style={{
          padding: '14px 18px', borderRadius: 14,
          background: t.text, color: t.bg,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          fontWeight: 700, fontSize: 14, letterSpacing: '0.01em',
        }}>
          <span>Save rating</span>
          <span style={{ fontFamily: SW_MONO, opacity: 0.7, fontSize: 12 }}>{answered}/{total}</span>
        </div>
      </div>
    </div>
  );
}

// ───────────────────────── Section accordion ─────────────────────────
function RatingSection({ t, section }) {
  const s = section;
  const ans = (s.criteria || []).filter(c => c.v != null).length;
  const tot = (s.criteria || []).length;
  return (
    <div style={{
      background: t.surface, borderRadius: 14,
      border: `0.5px solid ${t.border}`,
      overflow: 'hidden',
    }}>
      {/* Section header */}
      <div style={{
        padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14, fontWeight: 700, letterSpacing: '-0.01em', color: s.open ? t.up : t.text }}>
            {s.label}
          </div>
          <div style={{ fontSize: 11, color: t.textDim, fontFamily: SW_MONO, marginTop: 1 }}>
            {ans} of {tot} answered
          </div>
        </div>
        <div style={{
          width: 28, height: 28, borderRadius: 14,
          background: s.open ? t.up : t.chip,
          color: s.open ? '#fff' : t.textMuted,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          transform: s.open ? 'rotate(0deg)' : 'rotate(-180deg)',
          transition: 'transform 0.2s',
        }}>
          <svg width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="m3 7.5 3-3 3 3" />
          </svg>
        </div>
      </div>

      {/* Section body */}
      {s.open && (
        <div style={{ padding: '0 16px 12px' }}>
          {s.criteria.map((c, i) => (
            <CriterionRow key={c.id} t={t} criterion={c} first={i === 0} />
          ))}
        </div>
      )}
    </div>
  );
}

// ───────────────────────── One criterion row ─────────────────────────
function CriterionRow({ t, criterion, first }) {
  const c = criterion;
  // Color spectrum per grade (idx 0..4 = ++, +, ?, −, −−)
  const grades = [
    { label: '++', sel: t.up,         soft: t.upSoft,   hint: 'rgba(0,184,92,0.04)',  fg: t.up },
    { label: '+',  sel: t.up,         soft: t.upSoft,   hint: 'rgba(0,184,92,0.04)',  fg: t.up },
    { label: '?',  sel: t.textMuted,  soft: t.chip,     hint: t.chip,                  fg: t.textMuted },
    { label: '−',  sel: t.down,       soft: t.downSoft, hint: 'rgba(229,52,42,0.04)', fg: t.down },
    { label: '−−', sel: t.down,       soft: t.downSoft, hint: 'rgba(229,52,42,0.04)', fg: t.down },
  ];
  // For dark mode, hint tints need adjustment
  if (t.name === 'dark') {
    grades[0].hint = 'rgba(0,210,106,0.06)';
    grades[1].hint = 'rgba(0,210,106,0.06)';
    grades[3].hint = 'rgba(255,69,58,0.06)';
    grades[4].hint = 'rgba(255,69,58,0.06)';
  }
  return (
    <div style={{
      paddingTop: first ? 10 : 12,
      paddingBottom: 4,
      borderTop: first ? `0.5px solid ${t.border}` : 'none',
    }}>
      <div style={{ fontSize: 13.5, fontWeight: 500, color: t.text, marginBottom: 8, letterSpacing: '-0.005em' }}>
        {c.label}
      </div>
      <div style={{ display: 'flex', gap: 4 }}>
        {grades.map((g, i) => {
          const active = c.v === i;
          // Faded — when SOMETHING is selected and this isn't it
          const hasOther = c.v != null && !active;
          return (
            <div key={i} style={{
              flex: 1, padding: '10px 0', textAlign: 'center',
              borderRadius: 8,
              background: active ? g.sel : g.hint,
              color: active ? '#fff' : g.fg,
              fontFamily: SW_MONO, fontSize: 13, fontWeight: 700,
              border: active ? 'none' : `0.5px solid ${active ? 'transparent' : t.border}`,
              opacity: hasOther ? 0.45 : 1,
              letterSpacing: '0.02em',
            }}>{g.label}</div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { RatingForm });
