// Lottery detail screen — Top 5 AI, calc %, crowd picks, OCR mock

window.LotteryScreen = function LotteryScreen() {
  const { route, go, bumpCrowd, crowdExtra, addOcr, ocrHistory, tweaks } = useApp();
  const theme = useTheme();
  const slug = route.params.slug;
  const lot = MOCK_LOTTERIES.find(l => l.slug === slug);
  const top5 = MOCK_TOP5[slug] || [];
  const crowd = MOCK_CROWD[slug] || [];
  const { text: cd, totalMs } = useCountdown(lot?.close || '23:59');
  const closed = totalMs < 5000;

  const [calcInput, setCalcInput] = useState('');
  const [calcResult, setCalcResult] = useState(null);
  const [ocrState, setOcrState] = useState('idle'); // idle|loading|done
  const [ocrResult, setOcrResult] = useState(null);
  const fileRef = useRef();

  if (!lot) return <div>ไม่พบหวย</div>;

  const mergedCrowd = useMemo(() => {
    const extra = crowdExtra[slug] || {};
    return crowd.map(([n, c]) => [n, c + (extra[n] || 0)]).sort((a,b) => b[1] - a[1]);
  }, [crowd, crowdExtra, slug]);

  const calc = () => {
    const n = calcInput.trim();
    if (!n || !/^\d{2,3}$/.test(n)) {
      setCalcResult({ error: 'กรุณาใส่เลข 2-3 หลัก' });
      return;
    }
    // mock: confidence based on presence in top5 + hash
    const hit = top5.find(t => t.num === n);
    let pct, reason;
    if (hit) {
      pct = hit.confidence;
      reason = `เลข ${n} อยู่ใน Top 5 เลขเด่น AI อันดับที่ ${hit.rank}`;
    } else {
      const hash = n.split('').reduce((s,c) => s + c.charCodeAt(0), 0);
      pct = 15 + (hash % 38);
      reason = `เลข ${n} ปรากฏ ${3 + (hash % 5)} ครั้งจาก 30 งวดหลัง`;
    }
    setCalcResult({ num: n, pct, reason });
  };

  const pickCrowd = (num) => {
    if (closed) return;
    bumpCrowd(slug, num);
  };

  const runOcr = (file) => {
    setOcrState('loading');
    setTimeout(() => {
      // fake: generate 3-5 detected numbers
      const nums = [];
      const pool = ['23','56','89','47','12','78','34','65','90','01','45','67','28','91','03'];
      for (let i = 0; i < 4; i++) nums.push(pool[Math.floor(Math.random() * pool.length)]);
      const match = 55 + Math.floor(Math.random() * 40);
      const result = { file: file?.name || 'ใบแนวทาง.jpg', nums: [...new Set(nums)], match, time: new Date().toLocaleTimeString('th-TH', { hour: '2-digit', minute:'2-digit'}) };
      setOcrResult(result);
      setOcrState('done');
      addOcr({ slug, ...result });
    }, 1400);
  };

  return (
    <PhoneShell bg="#FAF7F2">
      {/* Header */}
      <div style={{
        padding: '14px 16px 12px', display: 'flex', alignItems: 'center', gap: 12,
        background: '#FAF7F2', position: 'sticky', top: 0, zIndex: 20,
        borderBottom: '1px solid #EDE7DC',
      }}>
        <button onClick={() => go('home')} style={{
          width: 38, height: 38, borderRadius: 999, border: 0, background: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          boxShadow: '0 1px 3px rgba(0,0,0,0.06)',
        }}><IconBack /></button>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ fontSize: 20 }}>{lot.flag}</span>
            <span style={{ fontSize: 17, fontWeight: 800, color: '#1A1A1A' }}>{lot.name}</span>
          </div>
          <div style={{ fontSize: 12, color: closed ? '#B91C1C' : '#8C8678', marginTop: 2, fontWeight: 500 }}>
            {closed ? 'ปิดรับแล้ว รอเปิดรอบใหม่' : `ปิดรับใน ${cd}`}
          </div>
        </div>
        <SpeakerBtn label="ฟังสรุป" onSpeak={() => `หวย ${lot.name} Top 5 เลขเด่นคือ ${top5.map(t => `อันดับ ${t.rank} เลข ${t.num} โอกาส ${t.confidence}%`).join(' , ')}`} />
      </div>

      {/* Section 1: Top 5 */}
      <Section title="Top 5 เลขเด่น AI" icon="🏆" dim={closed}>
        <Top5View items={top5} />
      </Section>

      {/* Section 2: calc % */}
      <Section title="ใส่เลขเพื่อคาดการณ์โอกาสถูก" icon="🎯" dim={closed}>
        <div style={{ background: '#fff', borderRadius: 14, padding: 16, border: '1px solid #EDE7DC' }}>
          <div style={{ display: 'flex', gap: 10 }}>
            <input
              value={calcInput}
              onChange={e => setCalcInput(e.target.value.replace(/\D/g,'').slice(0,3))}
              placeholder="เช่น 23 หรือ 456"
              inputMode="numeric"
              disabled={closed}
              style={{
                flex: 1, padding: '13px 14px', borderRadius: 11, border: '1.5px solid #E5DFD1',
                fontSize: 17, fontFamily: 'inherit', fontWeight: 600, letterSpacing: 2,
                textAlign: 'center', background: closed ? '#F5F0E6' : '#fff',
              }}
            />
            <button onClick={calc} disabled={closed} style={{
              padding: '0 18px', borderRadius: 11, border: 0,
              background: closed ? '#C4BEB0' : theme.accent, color: '#fff',
              fontSize: 14, fontWeight: 700, cursor: closed ? 'not-allowed' : 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap',
            }}>คำนวณ %</button>
          </div>
          {calcResult?.error && <div style={{ marginTop: 10, color: '#B91C1C', fontSize: 13 }}>{calcResult.error}</div>}
          {calcResult && !calcResult.error && (
            <div style={{ marginTop: 14, padding: 14, borderRadius: 12, background: `${theme.accent}0A`, border: `1px solid ${theme.accent}22` }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{
                  width: 62, height: 62, borderRadius: 14, background: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontWeight: 800, fontSize: 22, color: theme.accent,
                  border: `2px solid ${theme.accent}`,
                }}>{calcResult.num}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12, color: '#8C8678' }}>โอกาสถูกตามสถิติ</div>
                  <div style={{ fontSize: 28, fontWeight: 800, color: theme.accent, lineHeight: 1.1 }}>{calcResult.pct}%</div>
                </div>
                <PctRing value={calcResult.pct} color={theme.accent} />
              </div>
              <div style={{ marginTop: 10, fontSize: 13, color: '#5A5546', lineHeight: 1.5 }}>{calcResult.reason}</div>
            </div>
          )}
        </div>
      </Section>

      {/* Section 3: Crowd picks */}
      <Section title="เลขที่คนวิเคราะห์มากที่สุด" icon="📊">
        <div style={{ background: '#fff', borderRadius: 14, padding: 16, border: '1px solid #EDE7DC' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8 }}>
            {mergedCrowd.slice(0,10).map(([num, count], i) => {
              const maxCount = mergedCrowd[0][1];
              const t = count / maxCount;
              // heat: red (hot) -> gold -> blue (cold)
              let bg, fg;
              if (t > 0.66) { bg = theme.accent; fg = '#fff'; }
              else if (t > 0.33) { bg = `${theme.accent}22`; fg = theme.accent; }
              else { bg = '#F0F4F8'; fg = '#5A6A7A'; }
              return (
                <button key={num} onClick={() => pickCrowd(num)} style={{
                  aspectRatio: '1', borderRadius: 12, border: 0,
                  background: bg, color: fg,
                  display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                  cursor: 'pointer', fontFamily: 'inherit',
                }}>
                  <div style={{ fontSize: 20, fontWeight: 800 }}>{num}</div>
                  <div style={{ fontSize: 10, opacity: 0.85, marginTop: 1 }}>{count.toLocaleString()}</div>
                </button>
              );
            })}
          </div>
          <div style={{ marginTop: 10, fontSize: 11, color: '#A39B87', textAlign: 'center' }}>
            กดเลขเพื่อโหวตเพิ่ม • อัปเดตแบบ realtime
          </div>
        </div>
      </Section>

      {/* Section 4: OCR */}
      <Section title="สแกนรูปใบแนวทาง" icon="📷">
        <div style={{ background: '#fff', borderRadius: 14, padding: 16, border: '1px solid #EDE7DC' }}>
          <div style={{ fontSize: 13, color: '#5A5546', marginBottom: 10 }}>
            อัปโหลดรูปเพื่อตรวจว่าเลขในใบมีโอกาสถูกกี่ %
          </div>
          <input ref={fileRef} type="file" accept="image/*" style={{ display:'none' }} onChange={e => runOcr(e.target.files[0])} />
          <button onClick={() => { if (ocrState !== 'loading') runOcr({ name: 'ใบแนวทาง.jpg'}); }} style={{
            width: '100%', padding: '22px 16px', borderRadius: 14,
            border: `2px dashed ${theme.accent}55`, background: `${theme.accent}0A`,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
            cursor: 'pointer', fontFamily: 'inherit',
          }}>
            <IconCamera size={28} color={theme.accent} />
            <div style={{ fontWeight: 700, color: theme.accent, fontSize: 15 }}>เลือกรูป หรือลากมาวาง</div>
            <div style={{ fontSize: 11, color: '#8C8678' }}>รองรับ JPG, PNG — สูงสุด 10MB</div>
          </button>

          {ocrState === 'loading' && (
            <div style={{ marginTop: 12, padding: 14, background: `${theme.accent}0A`, borderRadius: 12, textAlign: 'center' }}>
              <div style={{
                width: 32, height: 32, margin: '0 auto 8px',
                border: `3px solid ${theme.accent}33`,
                borderTopColor: theme.accent, borderRadius: 999,
                animation: 'spin 0.8s linear infinite',
              }} />
              <div style={{ fontSize: 13, color: theme.accent, fontWeight: 600 }}>กำลังวิเคราะห์รูป...</div>
            </div>
          )}

          {ocrState === 'done' && ocrResult && (
            <div style={{ marginTop: 12, padding: 14, borderRadius: 12, background: '#F8FBF4', border: '1px solid #D4E8BC' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: '#15803D' }}>ตรวจเจอ {ocrResult.nums.length} เลข</div>
                <div style={{ fontSize: 13, color: '#16A34A', fontWeight: 700 }}>{ocrResult.match}% น่าถูก</div>
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {ocrResult.nums.map(n => (
                  <span key={n} style={{
                    padding: '6px 12px', borderRadius: 999,
                    background: '#fff', border: '1.5px solid #16A34A',
                    fontWeight: 800, color: '#15803D', fontSize: 14,
                  }}>{n}</span>
                ))}
              </div>
            </div>
          )}

          {ocrHistory.length > 0 && (
            <details style={{ marginTop: 12 }}>
              <summary style={{ fontSize: 13, color: '#8C8678', cursor: 'pointer', fontWeight: 600 }}>
                ประวัติล่าสุด ({ocrHistory.length})
              </summary>
              <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 6 }}>
                {ocrHistory.map((h, i) => (
                  <div key={i} style={{ padding: '8px 10px', background: '#F5F0E6', borderRadius: 8, fontSize: 12, color: '#5A5546', display: 'flex', justifyContent: 'space-between' }}>
                    <span>{h.file}</span>
                    <span style={{ color: '#16A34A', fontWeight: 700 }}>{h.match}%</span>
                  </div>
                ))}
              </div>
            </details>
          )}
        </div>
      </Section>

      <div style={{ height: 14 }} />
    </PhoneShell>
  );
};

function Section({ title, icon, children, dim }) {
  return (
    <div style={{ padding: '14px 16px 4px', opacity: dim ? 0.55 : 1 }}>
      <div style={{ fontSize: 14, fontWeight: 800, color: '#1A1A1A', marginBottom: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ fontSize: 18 }}>{icon}</span>{title}
      </div>
      {children}
    </div>
  );
}

// ── Top 5 variants ──
function Top5View({ items }) {
  const { tweaks } = useApp();
  const variant = tweaks.top5Style || 'vertical';
  if (variant === 'horizontal') return <Top5Horizontal items={items} />;
  if (variant === 'podium') return <Top5Podium items={items} />;
  return <Top5Vertical items={items} />;
}

function Top5Vertical({ items }) {
  const theme = useTheme();
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {items.map(t => (
        <div key={t.rank} style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: 14, borderRadius: 14,
          background: t.rank === 1 ? `linear-gradient(90deg, ${theme.gold}22, #fff)` : '#fff',
          border: `1px solid ${t.rank === 1 ? theme.gold : '#EDE7DC'}`,
        }}>
          <div style={{
            width: 32, height: 32, borderRadius: 999,
            background: t.rank <= 3 ? theme.gold : '#E5DFD1',
            color: t.rank <= 3 ? '#fff' : '#5A5546',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 14, fontWeight: 800, flexShrink: 0,
          }}>{t.rank}</div>
          <div style={{ minWidth: 72 }}>
            <div style={{ fontSize: 26, fontWeight: 800, color: theme.accent, lineHeight: 1 }}>{t.num}</div>
            <div style={{ fontSize: 10, color: '#8C8678', marginTop: 3, fontWeight: 600 }}>{t.type}</div>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12, color: '#5A5546', lineHeight: 1.4 }}>{t.desc}</div>
          </div>
          <div style={{ textAlign: 'right', flexShrink: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 3, justifyContent: 'flex-end' }}>
              <IconArrowUp />
              <span style={{ fontSize: 16, fontWeight: 800, color: '#16A34A' }}>{t.confidence}%</span>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function Top5Horizontal({ items }) {
  const theme = useTheme();
  return (
    <div style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '4px 0 8px', margin: '0 -16px', paddingLeft: 16, paddingRight: 16 }}>
      {items.map(t => (
        <div key={t.rank} style={{
          flexShrink: 0, width: 130, padding: 14, borderRadius: 14,
          background: '#fff', border: `1px solid ${t.rank === 1 ? theme.gold : '#EDE7DC'}`,
          display: 'flex', flexDirection: 'column', gap: 4,
          position: 'relative',
        }}>
          <div style={{
            position: 'absolute', top: 10, right: 10,
            width: 24, height: 24, borderRadius: 999,
            background: t.rank <= 3 ? theme.gold : '#E5DFD1',
            color: t.rank <= 3 ? '#fff' : '#5A5546',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 11, fontWeight: 800,
          }}>{t.rank}</div>
          <div style={{ fontSize: 32, fontWeight: 800, color: theme.accent, lineHeight: 1 }}>{t.num}</div>
          <div style={{ fontSize: 10, color: '#8C8678', fontWeight: 600 }}>{t.type}</div>
          <div style={{ fontSize: 11, color: '#5A5546', lineHeight: 1.4, marginTop: 2, minHeight: 30 }}>{t.desc}</div>
          <div style={{ marginTop: 6, display: 'flex', alignItems: 'center', gap: 3 }}>
            <IconArrowUp />
            <span style={{ fontSize: 13, fontWeight: 800, color: '#16A34A' }}>{t.confidence}%</span>
          </div>
        </div>
      ))}
    </div>
  );
}

function Top5Podium({ items }) {
  const theme = useTheme();
  const [p1, p2, p3, ...rest] = items;
  const podium = [
    { ...p2, height: 78, color: '#C0C0C0' },
    { ...p1, height: 100, color: theme.gold },
    { ...p3, height: 58, color: '#CD7F32' },
  ];
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, justifyContent: 'center', padding: '8px 0' }}>
        {podium.map((t) => (
          <div key={t.rank} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <div style={{ fontSize: 11, color: '#8C8678', fontWeight: 600 }}>{t.type}</div>
            <div style={{ fontSize: 28, fontWeight: 800, color: theme.accent, margin: '2px 0' }}>{t.num}</div>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#16A34A' }}>{t.confidence}%</div>
            <div style={{
              height: t.height, width: '100%', marginTop: 8,
              background: `linear-gradient(180deg, ${t.color}, ${t.color}CC)`,
              borderRadius: '10px 10px 0 0',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#fff', fontSize: 22, fontWeight: 800,
              boxShadow: `0 -2px 8px ${t.color}44`,
            }}>{t.rank}</div>
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 12 }}>
        {rest.map(t => (
          <div key={t.rank} style={{
            display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px',
            background: '#fff', border: '1px solid #EDE7DC', borderRadius: 12,
          }}>
            <div style={{ width: 24, height: 24, borderRadius: 999, background: '#E5DFD1', color: '#5A5546', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 800 }}>{t.rank}</div>
            <div style={{ fontSize: 20, fontWeight: 800, color: theme.accent, minWidth: 56 }}>{t.num}</div>
            <div style={{ flex: 1, fontSize: 11, color: '#5A5546' }}>{t.desc}</div>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#16A34A' }}>{t.confidence}%</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function PctRing({ value, color }) {
  const r = 22, c = 2 * Math.PI * r;
  const off = c - (value / 100) * c;
  return (
    <svg width="54" height="54" viewBox="0 0 54 54" style={{ flexShrink: 0 }}>
      <circle cx="27" cy="27" r={r} stroke={`${color}22`} strokeWidth="5" fill="none"/>
      <circle cx="27" cy="27" r={r} stroke={color} strokeWidth="5" fill="none"
        strokeDasharray={c} strokeDashoffset={off} strokeLinecap="round"
        transform="rotate(-90 27 27)" />
    </svg>
  );
}
