// Card detail modal — slim: Title + Labels + Dates + Description + Members + Comments
const DatePopover = ({ value, onChange, onClose }) => {
  const [start, setStart] = React.useState(value.start || '2026-05-08');
  const [due, setDue] = React.useState(value.due || '2026-05-15');
  const [time, setTime] = React.useState(value.time || '14:30');
  const [done, setDone] = React.useState(!!value.done);

  // Tiny static calendar
  const days = Array.from({length:31}, (_,i)=> i+1);
  const dueDay = parseInt(due.split('-')[2]);
  const startDay = parseInt(start.split('-')[2]);

  return (
    <div style={{position:'absolute', top:34, right:0, zIndex:60, width:300, padding:16, background:'var(--card-bg)', border:'1px solid var(--border-c)', borderRadius:'var(--radius)', boxShadow:'0 12px 32px hsl(0 0% 0% / .15)'}} onClick={e=>e.stopPropagation()}>
      <div className="row between" style={{marginBottom:12}}>
        <div style={{fontWeight:600, fontSize:14}}>Dates</div>
        <button className="btn btn-ghost btn-icon btn-sm" onClick={onClose}><Icon name="close" size={13}/></button>
      </div>
      <div style={{fontSize:13, fontWeight:500, marginBottom:8}}>May 2026</div>
      <div style={{display:'grid', gridTemplateColumns:'repeat(7, 1fr)', gap:2, fontSize:11, marginBottom:14}}>
        {['S','M','T','W','T','F','S'].map((d,i)=>(<div key={i} style={{textAlign:'center', color:'var(--muted-fg)', padding:'2px 0'}}>{d}</div>))}
        {Array.from({length:5}).map((_,i)=>(<div key={'pad'+i}/>))}
        {days.map(d=>{
          const inRange = d >= startDay && d <= dueDay;
          const isStart = d === startDay; const isDue = d === dueDay;
          return (
            <button key={d} onClick={()=>setDue(`2026-05-${String(d).padStart(2,'0')}`)} style={{
              padding:'4px 0', fontSize:12, border:'none',
              background: (isStart||isDue) ? 'var(--primary-c)' : (inRange ? 'hsl(var(--accent))' : 'transparent'),
              color: (isStart||isDue) ? 'var(--primary-fg)' : 'var(--fg)',
              borderRadius: isStart ? '999px 0 0 999px' : (isDue ? '0 999px 999px 0' : 0),
              cursor:'pointer'
            }}>{d}</button>
          );
        })}
      </div>
      <div className="col" style={{gap:8}}>
        <div><label className="label">Start date</label><input className="input" type="date" value={start} onChange={e=>setStart(e.target.value)}/></div>
        <div><label className="label">Due date</label><input className="input" type="date" value={due} onChange={e=>setDue(e.target.value)}/></div>
        <div><label className="label">Due time</label><input className="input" type="time" value={time} onChange={e=>setTime(e.target.value)}/></div>
        <label className="row" style={{gap:8, marginTop:4, cursor:'pointer'}}>
          <input type="checkbox" checked={done} onChange={e=>setDone(e.target.checked)}/>
          <span style={{fontSize:13}}>Mark as complete</span>
        </label>
      </div>
      <div className="row between" style={{marginTop:14}}>
        <button className="btn btn-ghost btn-sm" onClick={()=>{ onChange({}); onClose(); }}>Clear</button>
        <button className="btn btn-primary btn-sm" onClick={()=>{ onChange({start, due, time, done}); onClose(); }}>Save</button>
      </div>
    </div>
  );
};

const MembersPopover = ({ onClose, members, onToggle }) => {
  const candidates = [
    { id:'L', name:'Linh Tran', email:'linh@example.com' },
    { id:'M', name:'Minh Vu', email:'minh@example.com' },
    { id:'K', name:'Khanh Le', email:'khanh@example.com' },
    { id:'A', name:'An Pham', email:'an@example.com' },
  ];
  const [q, setQ] = React.useState('');
  const filtered = candidates.filter(c => c.name.toLowerCase().includes(q.toLowerCase()) || c.email.includes(q.toLowerCase()));
  return (
    <div style={{position:'absolute', top:34, left:0, zIndex:60, width:280, padding:12, background:'var(--card-bg)', border:'1px solid var(--border-c)', borderRadius:'var(--radius)', boxShadow:'0 12px 32px hsl(0 0% 0% / .15)'}} onClick={e=>e.stopPropagation()}>
      <div className="row between" style={{marginBottom:10}}>
        <div style={{fontWeight:600, fontSize:14}}>Members</div>
        <button className="btn btn-ghost btn-icon btn-sm" onClick={onClose}><Icon name="close" size={13}/></button>
      </div>
      <input className="input" placeholder="Search by name or email…" value={q} onChange={e=>setQ(e.target.value)} style={{marginBottom:8}}/>
      <div style={{display:'flex', flexDirection:'column', gap:2, maxHeight:220, overflow:'auto'}}>
        {filtered.map(c => (
          <button key={c.id} onClick={()=>onToggle(c.id)} className="row" style={{gap:10, padding:8, border:'none', background:'transparent', borderRadius:6, cursor:'pointer', textAlign:'left', color:'var(--fg)'}}
            onMouseEnter={e=>e.currentTarget.style.background='hsl(var(--accent))'} onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
            <Avatar name={c.id} size={26}/>
            <div style={{flex:1}}>
              <div style={{fontSize:13, fontWeight:500}}>{c.name}</div>
              <div className="muted" style={{fontSize:12}}>{c.email}</div>
            </div>
            {members.includes(c.id) && <Icon name="check" size={14}/>}
          </button>
        ))}
      </div>
    </div>
  );
};

const CardModal = ({ card, onClose }) => {
  if (!card) return null;
  const [dates, setDates] = React.useState({ start:'2026-05-08', due:'2026-05-15', time:'14:30', done:false });
  const [showDate, setShowDate] = React.useState(false);
  const [showMembers, setShowMembers] = React.useState(false);
  const [members, setMembers] = React.useState(['L','M','K']);
  const [comment, setComment] = React.useState('');

  const toggleMember = (id) => setMembers(prev => prev.includes(id) ? prev.filter(x=>x!==id) : [...prev, id]);

  const fmtDates = () => {
    if (!dates.due) return null;
    const m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    const d = new Date(dates.due);
    return `${m[d.getMonth()]} ${d.getDate()}${dates.time? ', '+dates.time:''}`;
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e=>e.stopPropagation()} style={{maxWidth:680}}>
        <div style={{padding:'24px 28px 8px', position:'relative'}}>
          <button className="btn btn-ghost btn-icon btn-sm" style={{position:'absolute', top:16, right:16}} onClick={onClose}><Icon name="close" size={16}/></button>
          <div className="muted" style={{fontSize:12, marginBottom:6}}>In list <span style={{color:'var(--fg)', fontWeight:500}}>In Progress</span></div>
          <div style={{fontSize:20, fontWeight:600, letterSpacing:'-0.015em', paddingRight:40, lineHeight:1.3}}>{card.title || 'Build Kanban drag-and-drop interactions'}</div>
        </div>

        <div style={{padding:'8px 28px 24px', display:'flex', flexDirection:'column', gap:24}}>

          {/* Quick row: Members + Labels + Dates */}
          <div className="row" style={{gap:24, flexWrap:'wrap', alignItems:'flex-start'}}>
            {/* Members */}
            <div style={{position:'relative'}}>
              <div className="muted" style={{fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:6}}>Members</div>
              <div className="row" style={{gap:4}}>
                {members.map(m => <Avatar key={m} name={m} size={28}/>)}
                <button onClick={()=>setShowMembers(true)} className="btn btn-ghost btn-icon btn-sm" style={{width:28, height:28, borderRadius:999, border:'1px dashed var(--border-c)'}}>
                  <Icon name="plus" size={12}/>
                </button>
              </div>
              {showMembers && <MembersPopover members={members} onToggle={toggleMember} onClose={()=>setShowMembers(false)}/>}
            </div>

            {/* Labels */}
            <div>
              <div className="muted" style={{fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:6}}>Labels</div>
              <div className="row" style={{gap:4, flexWrap:'wrap'}}>
                <span className="badge" style={{height:24, background:'#7c3aed22', color:'#7c3aed'}}>Design</span>
                <span className="badge" style={{height:24, background:'#16a34a22', color:'#16a34a'}}>Frontend</span>
                <button className="btn btn-ghost btn-icon btn-sm" style={{height:24, width:24, borderRadius:999, border:'1px dashed var(--border-c)'}}>
                  <Icon name="plus" size={11}/>
                </button>
              </div>
            </div>

            {/* Dates */}
            <div style={{position:'relative'}}>
              <div className="muted" style={{fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:6}}>Dates</div>
              <button className="btn btn-outline btn-sm" onClick={()=>setShowDate(s=>!s)}>
                <Icon name="calendar" size={13}/>
                {fmtDates() || 'Add dates'}
                {dates.done && <span className="badge" style={{height:18, background:'#dcfce7', color:'#15803d', marginLeft:4}}>Complete</span>}
              </button>
              {showDate && <DatePopover value={dates} onChange={setDates} onClose={()=>setShowDate(false)}/>}
            </div>
          </div>

          {/* Description */}
          <section>
            <div className="row between" style={{marginBottom:8}}>
              <div className="row" style={{gap:8, fontWeight:600, fontSize:14}}><Icon name="msg" size={15}/> Description</div>
              <button className="btn btn-ghost btn-sm">Edit</button>
            </div>
            <div style={{fontSize:14, lineHeight:1.6, padding:14, background:'hsl(var(--secondary) / .5)', borderRadius:'calc(var(--radius) - 2px)', border:'1px solid var(--border-c)', color:'var(--fg)'}}>
              Implement smooth drag-and-drop interactions for the Kanban board. Cards moveable between lists, lists reorder horizontally, with clear visual feedback during drag. Use <code style={{background:'hsl(var(--muted))',padding:'1px 5px',borderRadius:4,fontSize:13}}>@dnd-kit/core</code> for accessibility.
            </div>
          </section>

          {/* Comments */}
          <section>
            <div className="row" style={{gap:8, fontWeight:600, fontSize:14, marginBottom:12}}><Icon name="msg" size={15}/> Comments</div>
            <div className="row" style={{gap:10, alignItems:'flex-start', marginBottom:18}}>
              <Avatar name="L" size={30}/>
              <div style={{flex:1}}>
                <textarea className="textarea" placeholder="Write a comment…" value={comment} onChange={e=>setComment(e.target.value)} style={{minHeight:60}}/>
                {comment && (
                  <div className="row" style={{gap:6, marginTop:6}}>
                    <button className="btn btn-primary btn-sm">Save</button>
                    <button className="btn btn-ghost btn-sm" onClick={()=>setComment('')}>Cancel</button>
                  </div>
                )}
              </div>
            </div>

            <div style={{display:'flex', flexDirection:'column', gap:18}}>
              {[
                { name:'Minh Vu', a:'M', when:'2h ago', text:'I pushed the initial drag handler implementation. Still need to wire up touch gestures.', mine:false},
                { name:'Linh Tran', a:'L', when:'1d ago', text:'Created the card and added initial checklist. @Minh can you take the lead on this?', mine:true},
              ].map((c,i)=>(
                <div key={i} className="row" style={{gap:10, alignItems:'flex-start'}}>
                  <Avatar name={c.a} size={30}/>
                  <div style={{flex:1}}>
                    <div className="row" style={{gap:8, marginBottom:4}}>
                      <span style={{fontWeight:600, fontSize:13}}>{c.name}</span>
                      <span className="muted" style={{fontSize:12}}>{c.when}</span>
                    </div>
                    <div style={{fontSize:14, lineHeight:1.55, padding:12, background:'hsl(var(--secondary) / .5)', border:'1px solid var(--border-c)', borderRadius:'calc(var(--radius) - 2px)'}}>{c.text}</div>
                    {c.mine && (
                      <div className="row" style={{gap:10, marginTop:4}}>
                        <a style={{fontSize:12, color:'var(--muted-fg)', cursor:'pointer', textDecoration:'underline', textUnderlineOffset:3}}>Edit</a>
                        <a style={{fontSize:12, color:'var(--muted-fg)', cursor:'pointer', textDecoration:'underline', textUnderlineOffset:3}}>Delete</a>
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </section>
        </div>
      </div>
    </div>
  );
};

window.CardModal = CardModal;
