// DirectionC.jsx — "חוקר הנתונים" Map-first interactive explorer.
// The map + month strip are the primary controls; the detail panel reacts.
const { useState: useStateC } = React;

function MonthStrip({ filter, setFilter }) {
  const trend = EI.monthlyTrend({ year: filter.year, month: 0, district: filter.district });
  const max = Math.max(1, ...trend.map(t => t.closures));
  return (
    <div style={{ direction: 'rtl' }}>
      <div style={{ display: 'flex', gap: 5, alignItems: 'flex-end', height: 92 }}>
        {trend.map(t => {
          const on = filter.month === t.month;
          const h = 14 + (t.closures / max) * 64;
          return (
            <Tip key={t.month} label={`${EI.MONTHS[t.month - 1]}: ${t.closures} סגירות, ${eiFmt(t.fines)} קנסות · לחצו לסינון`}
              block style={{ flex: 1 }}>
              <div onClick={() => setFilter(f => ({ ...f, month: on ? 0 : t.month }))}
                style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
                <div style={{ width: '100%', height: h, borderRadius: 6, background: on ? '#D20035' : '#F0CDD5',
                  border: on ? '2px solid #8E0024' : '1px solid transparent', boxSizing: 'border-box', transition: 'all .2s' }} />
                <span style={{ fontWeight: on ? 800 : 600, fontSize: 11, color: on ? '#D20035' : '#9a9a98' }}>{EI.MONTHS[t.month - 1].slice(0, 3)}</span>
              </div>
            </Tip>
          );
        })}
      </div>
    </div>
  );
}

function DirectionC() {
  const [filter, setFilter] = useStateC({ year: 2025, month: 0, district: null });
  const [metric, setMetric] = useStateC('closures');
  const k = EI.kpis(filter);
  const rows = EI.byDistrict(filter);
  const buckets = EI.durationBuckets(filter);
  const sel = filter.district ? rows.find(r => r.key === filter.district) : null;
  const scopeLabel = sel ? `מחוז ${sel.name}` : 'כלל הארץ';

  const metricBtn = (key, txt) => (
    <button onClick={() => setMetric(key)}
      style={{ border: 'none', cursor: 'pointer', fontFamily: "'Assistant',sans-serif", fontWeight: 700, fontSize: 14,
        padding: '7px 16px', borderRadius: 999, background: metric === key ? '#1D1D1B' : '#fff',
        color: metric === key ? '#fff' : '#5B5B59', border: '1px solid', borderColor: metric === key ? '#1D1D1B' : '#E4E4E2' }}>{txt}</button>
  );
  const detailRow = (value, label, tip, opts = {}) => (
    <Tip label={tip} block>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12, padding: '14px 0', borderBottom: '1px solid #ECECEA', cursor: 'help' }}>
        <span style={{ fontWeight: 600, fontSize: 15, color: '#333' }}><Hoverable>{label}</Hoverable></span>
        <span style={{ fontWeight: 800, fontSize: 30, color: '#D20035', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>
          <CountUp value={value} decimals={opts.decimals || 0} suffix={opts.suffix || ''} />
        </span>
      </div>
    </Tip>
  );

  return (
    <div style={{ width: '100%', maxWidth: 1320, margin: '0 auto', fontFamily: "'Assistant',sans-serif", background: '#fff', direction: 'rtl', boxSizing: 'border-box' }}>
      {/* header */}
      <div style={{ padding: '30px 44px 20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24, borderBottom: '1px solid #ECECEA' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <ChainMark size={44} />
          <div>
            <h1 style={{ margin: 0, fontWeight: 800, fontSize: 36, color: '#D20035', letterSpacing: '-0.02em' }}>{EI.meta.title}</h1>
            <p style={{ margin: '2px 0 0', fontWeight: 700, fontSize: 17, color: '#1D1D1B' }}>חוקר הנתונים האינטראקטיבי</p>
          </div>
        </div>
        <img src="assets/tfht-logo.png" alt="המטה" style={{ height: 62, width: 'auto' }} />
      </div>

      <div style={{ padding: '16px 44px', background: '#FBFBFA', borderBottom: '1px solid #ECECEA' }}>
        <FilterBar filter={filter} setFilter={setFilter} />
      </div>

      {/* main: map (right/primary) + detail panel (left) */}
      <div style={{ padding: '26px 44px 18px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 34, alignItems: 'start' }}>
        {/* detail panel */}
        <div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
            <h3 style={{ margin: 0, fontWeight: 800, fontSize: 22, color: '#1D1D1B' }}>{scopeLabel}</h3>
            <span style={{ fontWeight: 700, fontSize: 14, color: '#5B5B59' }}>{filter.month ? `${EI.MONTHS[filter.month - 1]} ${filter.year}` : filter.year}</span>
          </div>
          <p style={{ margin: '0 0 6px', fontSize: 14, color: '#9a9a98', fontWeight: 600 }}>
            {sel ? 'בחרתם מחוז על המפה — הנתונים מסוננים אליו' : 'בחרו מחוז על המפה לפירוט'}
          </p>
          {detailRow(k.closures, 'סגירות מנהליות של בתי בושת', 'מספר צווי הסגירה המנהליים שהוצאו בתקופה ובמחוז הנבחרים.')}
          {detailRow(k.fines, 'קנסות שניתנו לצרכני זנות', 'קנסות ללקוחות זנות מכוח החוק לאיסור צריכת זנות (2018).')}
          {detailRow(k.reopened, 'בתי בושת שנפתחו בחזרה תוך חודש', 'נפתחו מחדש בתוך חודש מתום תוקף הצו — מדד לעמידות האכיפה.')}
          {detailRow(k.avgDuration, 'משך סגירה ממוצע', 'מספר הימים הממוצע שצו הסגירה היה בתוקף.', { suffix: ' ימים' })}
        </div>

        {/* map */}
        <div style={{ background: '#FBFBFA', border: '1px solid #ECECEA', borderRadius: 20, padding: '18px 22px' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
            <span style={{ fontWeight: 800, fontSize: 16, color: '#1D1D1B' }}>מפת אכיפה</span>
            <div style={{ display: 'flex', gap: 6 }}>{metricBtn('closures', 'סגירות')}{metricBtn('fines', 'קנסות')}</div>
          </div>
          <IsraelMap rows={rows} metric={metric} filter={filter} setFilter={setFilter} height={380} />
        </div>
      </div>

      {/* month strip */}
      <div style={{ padding: '6px 44px 24px' }}>
        <div style={{ background: '#fff', border: '1px solid #ECECEA', borderRadius: 18, padding: '18px 24px' }}>
          <SectionTitle sub="לחצו על חודש כדי לסנן את כל הנתונים. הגובה יחסי למספר הסגירות.">פילוח חודשי · {filter.year}</SectionTitle>
          <MonthStrip filter={filter} setFilter={setFilter} />
        </div>
      </div>

      {/* bar + duration */}
      <div style={{ padding: '0 44px 30px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 34, alignItems: 'start' }}>
        <div>
          <SectionTitle sub="לחצו על מחוז לסינון">{metric === 'closures' ? 'סגירות' : 'קנסות'} לפי מחוז</SectionTitle>
          <BarChart rows={rows} metric={metric} filter={filter} setFilter={setFilter} suffix={metric === 'fines' ? '' : ''} />
        </div>
        <div style={{ background: '#FBFBFA', border: '1px solid #ECECEA', borderRadius: 20, padding: '22px 24px' }}>
          <SectionTitle sub={`${k.reopened} מתוך ${k.closures} נפתחו בחזרה תוך חודש`}>כמה זמן בית בושת נשאר סגור?</SectionTitle>
          <DurationTimeline buckets={buckets} />
        </div>
      </div>

      <div style={{ padding: '0 44px 32px' }}><SourceNote /></div>
    </div>
  );
}
window.DirectionC = DirectionC;
