// Dream, Lucky, Profile screens

window.DreamScreen = function DreamScreen() {
  const { dreamHistory, addDream } = useApp();
  const theme = useTheme();
  const [text, setText] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);
  const [listening, setListening] = useState(false);

  const analyze = async () => {
    if (!text.trim()) return;
    setLoading(true);
    setResult(null);
    const time = new Date().toLocaleTimeString('th-TH', { hour:'2-digit', minute:'2-digit'});
    try {
      const data = await window.api.searchDream(text);
      const matched = window.mapDreamMatches(data?.matched_keywords);
      const r = { text, matched, time };
      setResult(r);
      if (matched.length > 0) addDream(r);
    } catch (e) {
      // graceful fallback to local keyword match if API unavailable
      const matched = MOCK_DREAMS.filter(d => text.includes(d.keyword));
      const r = { text, matched, time };
      setResult(r);
      if (matched.length > 0) addDream(r);
    } finally {
      setLoading(false);
    }
  };

  const startMic = () => {
    // visual mock — we won't actually reach mic perms in sandbox
    setListening(true);
    setTimeout(() => {
      setText(t => t + (t ? ' ' : '') + 'ฝันเห็นงูตัวใหญ่สีทองเลื้อยเข้ามาในบ้าน');
      setListening(false);
    }, 1800);
  };

  return (
    <PhoneShell>
      <div style={{ padding: '16px 20px 8px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ fontSize: 22, fontWeight: 800, color: '#1A1A1A', flex: 1 }}>🌙 ทำนายฝัน</div>
        <SpeakerBtn label="ฟัง" onSpeak={() => 'ทำนายความฝันด้วย AI เล่าความฝันของคุณ'} />
      </div>

      <div style={{ padding: '0 20px' }}>
        <div style={{
          padding: 18, borderRadius: 20,
          background: `linear-gradient(135deg, ${theme.accentDark}, ${theme.accent})`,
          color: '#fff', position: 'relative', overflow: 'hidden',
        }}>
          <div style={{ position: 'absolute', right: -10, top: -10, fontSize: 120, opacity: 0.08 }}>🌙</div>
          <div style={{ fontSize: 17, fontWeight: 800, position: 'relative' }}>เล่าความฝันของคุณ</div>
          <div style={{ fontSize: 13, opacity: 0.9, marginTop: 4, position: 'relative' }}>AI จะตีเป็นเลขให้คุณ 🌕</div>

          <div style={{ marginTop: 14, position: 'relative' }}>
            <textarea
              value={text}
              onChange={e => setText(e.target.value)}
              placeholder="เช่น ฝันเห็นงูใหญ่สีทอง ว่ายน้ำในบ้านเก่า..."
              rows={4}
              style={{
                width: '100%', boxSizing: 'border-box', padding: 14,
                borderRadius: 12, border: 0, resize: 'none',
                fontFamily: 'inherit', fontSize: 15, lineHeight: 1.5,
                background: 'rgba(255,255,255,0.97)', color: '#1A1A1A',
              }}
            />
            <button onClick={startMic} style={{
              position: 'absolute', right: 10, bottom: 12,
              width: 40, height: 40, borderRadius: 999, border: 0, cursor: 'pointer',
              background: listening ? '#DC2626' : theme.accentDark,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: listening ? '0 0 0 6px #DC262633' : 'none',
              animation: listening ? 'pulse 1.2s infinite' : 'none',
            }}>
              <IconMic color="#fff" size={18} />
            </button>
          </div>

          <button onClick={analyze} disabled={!text.trim() || loading} style={{
            width: '100%', marginTop: 12, padding: '14px', borderRadius: 12,
            background: '#fff', color: theme.accent, border: 0,
            fontSize: 16, fontWeight: 800, cursor: text.trim() ? 'pointer' : 'not-allowed',
            opacity: text.trim() ? 1 : 0.5, fontFamily: 'inherit',
          }}>
            {loading ? 'กำลังวิเคราะห์...' : '✨ วิเคราะห์ฝัน AI'}
          </button>
        </div>
      </div>

      {result && (
        <div style={{ padding: '16px 20px 8px' }}>
          {result.matched.length === 0 ? (
            <div style={{ padding: 16, background: '#FEF9C3', borderRadius: 12, border: '1px solid #FDE68A', fontSize: 13, color: '#92400E' }}>
              ยังไม่มีความฝันนี้ในระบบ ลองอธิบายใหม่หรือใช้คำอื่น
            </div>
          ) : (
            <>
              <div style={{ fontSize: 13, fontWeight: 700, color: '#5A5546', marginBottom: 10 }}>เจอ {result.matched.length} คำสำคัญ</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {result.matched.map(d => (
                  <div key={d.keyword} style={{ background:'#fff', borderRadius: 14, border: '1px solid #EDE7DC', overflow: 'hidden' }}>
                    <div style={{ padding: '12px 16px', background: `${theme.accent}0A`, display: 'flex', alignItems: 'center', gap: 10, borderBottom: '1px solid #EDE7DC' }}>
                      <div style={{ fontSize: 20 }}>🔮</div>
                      <div style={{ fontSize: 18, fontWeight: 800, color: '#1A1A1A' }}>{d.keyword}</div>
                      <div style={{ marginLeft: 'auto', fontSize: 11, color: '#8C8678', padding: '3px 8px', background: '#fff', borderRadius: 6 }}>{d.category}</div>
                    </div>
                    <div style={{ padding: 14 }}>
                      <div style={{ fontSize: 13, color: '#5A5546', lineHeight: 1.6, marginBottom: 10 }}>{d.meaning}</div>
                      <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
                        <NumGroup label="2 ตัว" nums={d.nums2} color={theme.accent} />
                        <NumGroup label="3 ตัว" nums={d.nums3} color={theme.gold} />
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>
      )}

      {dreamHistory.length > 0 && (
        <details style={{ margin: '8px 20px 20px', padding: '10px 14px', background: '#fff', borderRadius: 12, border: '1px solid #EDE7DC' }}>
          <summary style={{ fontSize: 13, fontWeight: 700, color: '#5A5546', cursor: 'pointer' }}>ประวัติล่าสุด ({dreamHistory.length})</summary>
          <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 8 }}>
            {dreamHistory.map((h, i) => (
              <div key={i} style={{ fontSize: 12, color: '#5A5546', padding: '8px 10px', background: '#FAF7F2', borderRadius: 8 }}>
                <div style={{ color: '#8C8678', fontSize: 10 }}>{h.time}</div>
                <div style={{ marginTop: 2 }}>"{h.text.slice(0, 60)}{h.text.length > 60 ? '...' : ''}"</div>
                <div style={{ marginTop: 4, fontWeight: 700, color: theme.accent }}>
                  {h.matched.map(m => m.keyword).join(', ')}
                </div>
              </div>
            ))}
          </div>
        </details>
      )}
    </PhoneShell>
  );
};

function NumGroup({ label, nums, color }) {
  return (
    <div style={{ flex: 1, minWidth: 120 }}>
      <div style={{ fontSize: 11, color: '#8C8678', fontWeight: 600, marginBottom: 6 }}>{label}</div>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {nums.map(n => (
          <div key={n} style={{
            padding: '6px 12px', borderRadius: 10,
            background: `${color}18`, color,
            fontWeight: 800, fontSize: 15,
          }}>{n}</div>
        ))}
      </div>
    </div>
  );
}

// ─── Lucky screen ───
window.LuckyScreen = function LuckyScreen() {
  const { luckyResult, setLuckyResult } = useApp();
  const theme = useTheme();
  const [bd, setBd] = useState('');

  const calc = async () => {
    if (!bd) return;
    const d = new Date(bd);
    try {
      const data = await window.api.lucky(bd);
      setLuckyResult({
        life: data.life_number,
        nums2: data.lucky_2_digits || [],
        nums3: data.lucky_3_digits || [],
        meaning: {
          title: data.life_meaning?.title || '',
          desc: data.life_meaning?.description || '',
        },
        birth: formatThaiDate(d),
      });
    } catch (e) {
      // graceful fallback to local computation if API unavailable
      const digits = String(d.getDate()) + String(d.getMonth()+1) + String(d.getFullYear());
      let life = digits.split('').reduce((s,n) => s + parseInt(n,10), 0);
      while (life > 9) life = String(life).split('').reduce((s,n) => s + parseInt(n,10), 0);
      const seed = d.getTime();
      const rnd = (i) => String(Math.floor(Math.abs(Math.sin(seed * (i+1))) * 100)).padStart(2,'0');
      const rnd3 = (i) => String(Math.floor(Math.abs(Math.sin(seed * (i+7))) * 1000)).padStart(3,'0');
      setLuckyResult({
        life,
        nums2: [rnd(1), rnd(2), rnd(3), rnd(4), rnd(5)],
        nums3: [rnd3(1), rnd3(2), rnd3(3)],
        meaning: MOCK_LIFE_NUMBERS[life],
        birth: formatThaiDate(d),
      });
    }
  };

  return (
    <PhoneShell>
      <div style={{ padding: '16px 20px 8px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ fontSize: 22, fontWeight: 800, color: '#1A1A1A', flex: 1 }}>⭐ เลขมงคล</div>
        <SpeakerBtn label="ฟัง" />
      </div>

      <div style={{ padding: '0 20px' }}>
        <div style={{
          padding: 18, borderRadius: 20,
          background: `linear-gradient(135deg, ${theme.gold}, #B8934A)`,
          color: '#fff',
        }}>
          <div style={{ fontSize: 17, fontWeight: 800 }}>เลขมงคลส่วนตัว</div>
          <div style={{ fontSize: 13, opacity: 0.95, marginTop: 4 }}>ป้อนวันเกิดของคุณ AI จะคำนวณเลขมงคลเฉพาะ</div>
          <input
            type="date"
            value={bd}
            onChange={e => setBd(e.target.value)}
            style={{
              width: '100%', boxSizing: 'border-box', marginTop: 14,
              padding: 14, borderRadius: 12, border: 0,
              fontFamily: 'inherit', fontSize: 16, fontWeight: 600,
              background: 'rgba(255,255,255,0.97)', color: '#1A1A1A',
            }}
          />
          <button onClick={calc} disabled={!bd} style={{
            width: '100%', marginTop: 10, padding: 14, borderRadius: 12,
            background: '#1A1A1A', color: '#fff', border: 0,
            fontSize: 16, fontWeight: 800, cursor: bd ? 'pointer' : 'not-allowed',
            opacity: bd ? 1 : 0.5, fontFamily: 'inherit',
          }}>✨ คำนวณเลขมงคล</button>
        </div>
      </div>

      {luckyResult && (
        <div style={{ padding: '16px 20px 8px' }}>
          <div style={{
            background: '#fff', borderRadius: 16, padding: 18,
            border: `1px solid ${theme.gold}55`,
          }}>
            <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
              <div style={{
                width: 78, height: 78, borderRadius: 20,
                background: `linear-gradient(135deg, ${theme.gold}, #B8934A)`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#fff', fontSize: 38, fontWeight: 800,
                boxShadow: `0 8px 16px ${theme.gold}55`,
              }}>{luckyResult.life}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 11, color: '#8C8678' }}>เลขชีวิตของคุณ</div>
                <div style={{ fontSize: 20, fontWeight: 800, color: '#1A1A1A' }}>{luckyResult.meaning.title}</div>
                <div style={{ fontSize: 12, color: '#8C8678', marginTop: 2 }}>เกิดวันที่ {luckyResult.birth}</div>
              </div>
            </div>
            <div style={{ marginTop: 12, padding: 12, background: '#FAF7F2', borderRadius: 10, fontSize: 13, color: '#5A5546', lineHeight: 1.6 }}>
              {luckyResult.meaning.desc}
            </div>
          </div>

          <div style={{ marginTop: 14, background: '#fff', borderRadius: 16, padding: 16, border: '1px solid #EDE7DC' }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#5A5546', marginBottom: 10 }}>เลขมงคล 2 ตัว (5 คู่)</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8 }}>
              {luckyResult.nums2.map((n, i) => (
                <div key={i} style={{
                  padding: '12px 6px', borderRadius: 12, textAlign: 'center',
                  background: `${theme.accent}10`, color: theme.accent,
                  fontSize: 20, fontWeight: 800,
                }}>{n}</div>
              ))}
            </div>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#5A5546', margin: '16px 0 10px' }}>เลขมงคล 3 ตัว</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
              {luckyResult.nums3.map((n, i) => (
                <div key={i} style={{
                  padding: '14px 6px', borderRadius: 12, textAlign: 'center',
                  background: `${theme.gold}20`, color: '#8B6914',
                  fontSize: 20, fontWeight: 800,
                }}>{n}</div>
              ))}
            </div>
          </div>
        </div>
      )}

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

// ─── Profile ───
window.ProfileScreen = function ProfileScreen() {
  const { user, logout, go, speakerOn, setSpeakerOn } = useApp();
  const theme = useTheme();
  return (
    <PhoneShell>
      <div style={{ padding: '16px 20px 8px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ fontSize: 22, fontWeight: 800, color: '#1A1A1A', flex: 1 }}>โปรไฟล์</div>
      </div>

      <div style={{ padding: '0 20px' }}>
        <div style={{
          background: `linear-gradient(135deg, ${theme.accent}, ${theme.accentDark})`,
          borderRadius: 20, padding: 20, color: '#fff',
          display: 'flex', alignItems: 'center', gap: 14,
        }}>
          <div style={{
            width: 62, height: 62, borderRadius: 999,
            background: 'rgba(255,255,255,0.25)', backdropFilter: 'blur(8px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 26, fontWeight: 800,
          }}>{user?.name?.[0]}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 18, fontWeight: 800 }}>{user?.name}</div>
            <div style={{ fontSize: 13, opacity: 0.9, marginTop: 2 }}>{formatPhone(user?.phone || '')}</div>
          </div>
        </div>
      </div>

      <div style={{ padding: '16px 20px 8px' }}>
        <MenuGroup title="บัญชีของฉัน">
          <MenuRow icon="✏️" label="แก้ไขชื่อแสดง" />
          <MenuRow icon="🎂" label="วันเกิด (สำหรับเลขมงคล)" detail="ตั้งค่า" />
        </MenuGroup>
        <MenuGroup title="ตั้งค่า">
          <MenuRow icon="🔊" label="เสียงอัตโนมัติเมื่อเข้าหน้า" toggle={speakerOn} onToggle={() => setSpeakerOn(!speakerOn)} />
          <MenuRow icon="📊" label="ประวัติการใช้งาน" />
          <MenuRow icon="ℹ️" label="เกี่ยวกับแอป" detail="v1.0.2" />
        </MenuGroup>
        {user?.isAdmin && (
          <MenuGroup title="ผู้ดูแลระบบ">
            <MenuRow icon="🛠️" label="ไปหน้า Admin" onClick={() => go('admin')} />
          </MenuGroup>
        )}
        <button onClick={logout} style={{
          width: '100%', marginTop: 6, padding: 14, borderRadius: 14,
          border: '1.5px solid #FECACA', background: '#fff', color: '#B91C1C',
          fontSize: 15, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
        }}>ออกจากระบบ</button>
      </div>
      <div style={{ height: 20 }} />
    </PhoneShell>
  );
};

function formatPhone(d) {
  if (!d || d.length < 10) return d;
  return `${d.slice(0,3)}-${d.slice(3,6)}-${d.slice(6)}`;
}

function MenuGroup({ title, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{ fontSize: 11, color: '#8C8678', textTransform: 'uppercase', fontWeight: 700, margin: '0 4px 8px', letterSpacing: 0.4 }}>{title}</div>
      <div style={{ background: '#fff', borderRadius: 14, border: '1px solid #EDE7DC', overflow: 'hidden' }}>
        {children}
      </div>
    </div>
  );
}

function MenuRow({ icon, label, detail, toggle, onToggle, onClick }) {
  return (
    <div onClick={onClick || onToggle} style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
      borderBottom: '1px solid #F5F0E6', cursor: 'pointer',
    }}>
      <div style={{ width: 30, textAlign: 'center', fontSize: 18 }}>{icon}</div>
      <div style={{ flex: 1, fontSize: 15, color: '#1A1A1A', fontWeight: 500 }}>{label}</div>
      {toggle !== undefined ? (
        <div style={{
          width: 44, height: 26, borderRadius: 999,
          background: toggle ? '#16A34A' : '#D4CCB8', position: 'relative',
          transition: 'background 0.2s',
        }}>
          <div style={{
            position: 'absolute', top: 2, left: toggle ? 20 : 2,
            width: 22, height: 22, borderRadius: 999, background: '#fff',
            transition: 'left 0.2s', boxShadow: '0 1px 2px rgba(0,0,0,0.15)',
          }} />
        </div>
      ) : (
        <>
          {detail && <div style={{ fontSize: 13, color: '#8C8678' }}>{detail}</div>}
          <div style={{ color: '#C4BEB0' }}>›</div>
        </>
      )}
    </div>
  );
}
