// History drawer — real chat history + real user footer
function HistoryDrawer({ open, onClose, chats, activeId, onSelect, onNewChat, onOpenSettings, onOpenSearch, tier, user, onUpgrade }) {
  const S = window.SOL;
  const SolunceLogo = ({ size=22 }) => (
    <svg width={size} height={size} viewBox="0 0 32 32" style={{ display:'block', flexShrink:0 }}>
      <circle cx="16" cy="16" r="14" fill={S.ink}/>
      <circle cx="16" cy="16" r="12" fill="none" stroke={S.cream} strokeOpacity="0.95" strokeWidth="0.6"/>
      {[0,1,2,3].map(i => {
        const a=(i/4)*Math.PI;
        return <line key={i} x1={16+Math.cos(a)*11.6} y1={16+Math.sin(a)*11.6} x2={16-Math.cos(a)*11.6} y2={16-Math.sin(a)*11.6} stroke={S.cream} strokeOpacity="0.95" strokeWidth="0.6" strokeLinecap="round"/>;
      })}
    </svg>
  );

  const pinned = (chats||[]).filter(c=>c.pinned);
  const rest   = (chats||[]).filter(c=>!c.pinned);
  const displayName = user?.display_name || user?.email?.split('@')[0] || 'Guest';
  const initial = displayName[0]?.toUpperCase() || '?';

  return (
    <div style={{ position:'absolute', inset:0, zIndex:30, pointerEvents:open?'auto':'none' }}>
      <div onClick={onClose} style={{ position:'absolute', inset:0, background:'rgba(28,26,23,0.32)', opacity:open?1:0, transition:'opacity 0.2s ease' }}/>
      <div style={{ position:'absolute', top:0, bottom:0, left:0, width:'84%', background:S.cream, boxShadow:'6px 0 32px rgba(28,26,23,0.12)', transform:open?'translateX(0)':'translateX(-100%)', transition:'transform 0.25s cubic-bezier(0.2,0.8,0.2,1)', display:'flex', flexDirection:'column' }}>

        <div style={{ height:'env(safe-area-inset-top, 44px)', minHeight:44 }}/>

        {/* Brand row */}
        <div style={{ padding:'8px 18px 14px', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <div style={{ display:'flex', alignItems:'center', gap:8 }}>
            <SolunceLogo size={22}/>
            <span style={{ fontFamily:S.sans, fontSize:13, fontWeight:600, letterSpacing:0.5, textTransform:'uppercase', color:S.ink }}>Solunce</span>
          </div>
          <button onClick={onClose} style={{ width:36, height:36, borderRadius:10, border:'none', background:'transparent', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
            <Icon name="close" size={20} color={S.ink2}/>
          </button>
        </div>

        {/* Search + New */}
        <div style={{ padding:'0 18px', display:'flex', flexDirection:'column', gap:8 }}>
          <button onClick={onOpenSearch} style={{ height:42, borderRadius:12, border:`1px solid ${S.line2}`, background:S.paper, display:'flex', alignItems:'center', gap:10, padding:'0 12px', fontFamily:S.sans, fontSize:14, color:S.ink3, cursor:'pointer' }}>
            <Icon name="search" size={17} color={S.ink3}/><span>Search chats</span>
          </button>
          <button onClick={onNewChat} style={{ height:46, borderRadius:12, border:'none', background:S.ink, color:S.cream, display:'flex', alignItems:'center', justifyContent:'center', gap:8, fontFamily:S.sans, fontSize:14.5, fontWeight:500, cursor:'pointer' }}>
            <Icon name="plus" size={18} color={S.cream}/> New chat
          </button>
        </div>

        {/* Chat list */}
        <div style={{ flex:1, overflowY:'auto', padding:'18px 10px 20px' }}>
          {pinned.length>0&&(
            <>
              <SectionLabel>Pinned</SectionLabel>
              {pinned.map(c=><ChatRow key={c.id} chat={c} active={c.id===activeId} onSelect={()=>{onSelect(c.id);onClose();}}/>)}
              <div style={{height:10}}/>
            </>
          )}
          {rest.length>0&&(
            <>
              <SectionLabel>Recent</SectionLabel>
              {rest.map(c=><ChatRow key={c.id} chat={c} active={c.id===activeId} onSelect={()=>{onSelect(c.id);onClose();}}/>)}
            </>
          )}
          {chats.length===0&&(
            <div style={{ padding:'20px 10px', fontFamily:S.sans, fontSize:13, color:S.ink3, textAlign:'center' }}>No chats yet</div>
          )}
        </div>

        {/* Footer */}
        <div style={{ borderTop:`1px solid ${S.line}`, padding:'12px 16px', display:'flex', alignItems:'center', gap:10, paddingBottom:'calc(12px + env(safe-area-inset-bottom, 0px))' }}>
          <div style={{ width:38, height:38, borderRadius:12, background:`linear-gradient(135deg, ${S.sun}, ${S.amberDeep})`, display:'flex', alignItems:'center', justifyContent:'center', color:S.cream, fontFamily:S.serif, fontSize:18, fontWeight:500, flexShrink:0 }}>
            {initial}
          </div>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontFamily:S.sans, fontSize:14, fontWeight:500, color:S.ink, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{displayName}</div>
            <div style={{ fontFamily:S.mono, fontSize:10, color:S.ink3, letterSpacing:0.4, textTransform:'uppercase' }}>
              {tier==='plus'?'Plus plan':tier==='trial'?'Trial':'Free plan'}
            </div>
          </div>
          {tier!=='plus'&&(
            <button onClick={onUpgrade} style={{ padding:'7px 12px', borderRadius:999, border:'none', background:S.ink, color:S.cream, fontFamily:S.sans, fontSize:12, fontWeight:500, cursor:'pointer', flexShrink:0 }}>Upgrade</button>
          )}
          <button onClick={onOpenSettings} style={{ width:36, height:36, borderRadius:10, border:'none', background:'transparent', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
            <Icon name="settings" size={18} color={S.ink2}/>
          </button>
        </div>
      </div>
    </div>
  );
}

function SectionLabel({ children }) {
  const S = window.SOL;
  return <div style={{ padding:'6px 10px 4px', fontFamily:S.mono, fontSize:10, letterSpacing:0.8, color:S.ink3, textTransform:'uppercase' }}>{children}</div>;
}

function ChatRow({ chat, active, onSelect }) {
  const S = window.SOL;
  const timeStr = chat.time || (chat.date ? new Intl.DateTimeFormat('en',{month:'short',day:'numeric'}).format(new Date(chat.date)) : '');
  return (
    <button onClick={onSelect} style={{ width:'100%', textAlign:'left', padding:'8px 10px', borderRadius:10, border:'none', background:active?S.cream2:'transparent', cursor:'pointer', display:'flex', alignItems:'flex-start', gap:10, marginBottom:2 }}>
      <SunMark size={18} variant={chat.model||'solus'} style={{ marginTop:3, flexShrink:0 }}/>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontFamily:S.sans, fontSize:14, fontWeight:500, color:S.ink, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', letterSpacing:-0.1 }}>{chat.title}</div>
        <div style={{ fontFamily:S.sans, fontSize:12, color:S.ink3, marginTop:1, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{chat.preview||''}</div>
      </div>
      <div style={{ fontFamily:S.mono, fontSize:10, color:S.ink3, marginTop:4, whiteSpace:'nowrap', flexShrink:0 }}>{timeStr}</div>
    </button>
  );
}

window.HistoryDrawer = HistoryDrawer;
