// v2 Home — Claude-Design–style project picker (real backend)

const V2HomeStage = ({ projects, user, onOpenProject, onNewProject }) => {
  const [recentTab, setRecentTab] = React.useState('Recent');
  const [search, setSearch] = React.useState('');
  const [name, setName] = React.useState('');
  const [creating, setCreating] = React.useState(false);

  const list = (projects || []).map(p => ({
    id: p.id,
    name: p.name,
    sub: `${p.client || ''} ${p.created_at ? '· ' + new Date(p.created_at).toLocaleDateString() : ''}`.trim(),
    when: p.created_at ? new Date(p.created_at).toLocaleDateString() : 'Recent',
    scope: p._scope || 'mine',
    isOwner: !!p._is_owner,
    fileCount: (p.folders || []).reduce((n,f) => n + (f.files||[]).length, 0),
    raw: p,
  }));

  const filtered = list.filter(p => {
    if (recentTab === 'Your Projects' && p.scope !== 'mine') return false;
    if (recentTab === 'Team' && p.scope !== 'team') return false;
    return !search || p.name.toLowerCase().includes(search.toLowerCase());
  });

  const showTutorial = recentTab === 'Recent' && !search;

  const create = async () => {
    if (!name.trim() || creating) return;
    setCreating(true);
    try { await onNewProject({client:'', name: name.trim(), brief:''}); setName(''); }
    finally { setCreating(false); }
  };

  return (
    <div className="v2-app" style={{height:'100%', display:'grid', gridTemplateColumns:'320px 1fr', overflow:'hidden'}}>
      {/* LEFT RAIL */}
      <aside style={{borderRight:'1px solid var(--rule)', background:'var(--paper)', display:'flex', flexDirection:'column'}}>
        <div style={{height:65, padding:'0 26px', borderBottom:'1px solid var(--rule)', display:'flex', alignItems:'center'}}>
          <span style={{fontFamily:'var(--font-mono)',fontSize:15,fontWeight:700,letterSpacing:'.18em'}}>PALETTE</span>
          <span style={{fontFamily:'var(--font-mono)',fontSize:14,fontWeight:400,letterSpacing:'.06em',color:'var(--muted)',marginLeft:10}}>Mosaic</span>
        </div>
        <div style={{padding:'20px 22px', flex:1}}>
          <div style={{fontSize:13.5, fontWeight:600, marginBottom:14}}>New Project</div>
          <label className="mono" style={{display:'block', fontSize:9.5, color:'var(--muted)', letterSpacing:'.08em', marginBottom:6}}>PROJECT NAME</label>
          <input value={name} onChange={e=>setName(e.target.value)}
            onKeyDown={e=>{ if (e.key==='Enter') create(); }}
            placeholder="e.g. HAZZYS ROWING CLUB"
            style={{width:'100%', padding:'10px 12px', border:'1px solid var(--rule-2)', borderRadius:8,
              background:'var(--paper-2)', fontSize:13, fontFamily:'inherit', outline:'none'}}/>
          <button onClick={create} disabled={!name.trim()||creating}
            style={{marginTop:18, width:'100%', padding:'11px 14px',
              background: name.trim() ? 'var(--primary)' : 'rgba(0,103,71,.32)',
              color:'#fff', border:'none', borderRadius:8, fontSize:13, fontWeight:600,
              cursor: name.trim()&&!creating ? 'pointer':'default',
              display:'flex', alignItems:'center', justifyContent:'center', gap:8}}>
            {creating ? <><V2Spinner size="sm" color="#fff"/> <span>만드는 중…</span></> : <>+ Create</>}
          </button>
          {user && (
            <div style={{marginTop:24,padding:'12px 14px',borderTop:'1px solid var(--rule)'}}>
              <div className="mono" style={{fontSize:9.5,color:'var(--muted)',letterSpacing:'.08em',marginBottom:4}}>SIGNED IN AS</div>
              <div style={{fontSize:12.5,fontWeight:500}}>{user.name || user.email}</div>
              <div style={{fontSize:11,color:'var(--muted)',marginTop:2}}>{user.role}</div>
            </div>
          )}
        </div>
      </aside>

      {/* RIGHT MAIN */}
      <main style={{display:'flex', flexDirection:'column', overflow:'hidden'}}>
        <div style={{height:65, display:'flex', alignItems:'center', gap:24, padding:'0 36px', borderBottom:'1px solid var(--rule)'}}>
          <div style={{flex:1}}/>
          <div style={{position:'relative', width:280}}>
            <span style={{position:'absolute', left:11, top:9, pointerEvents:'none'}}><V2Icon name="search" size={12} color="var(--muted)"/></span>
            <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Search"
              style={{width:'100%', padding:'8px 12px 8px 32px', border:'1px solid var(--rule)', borderRadius:8,
                background:'var(--paper)', fontSize:12, fontFamily:'inherit', outline:'none'}}/>
          </div>
        </div>

        <div style={{padding:'18px 36px 14px', display:'flex', gap:6}}>
          {['Recent','Your Projects','Team'].map(t => (
            <button key={t} onClick={()=>setRecentTab(t)} style={{
              padding:'5px 12px', borderRadius:14,
              border:'1px solid', borderColor: recentTab===t?'var(--ink)':'var(--rule)',
              background: recentTab===t?'var(--ink)':'transparent',
              color: recentTab===t?'#fff':'var(--sub)',
              fontSize:11.5, fontWeight: recentTab===t?600:500, cursor:'pointer', fontFamily:'inherit',
            }}>{t}</button>
          ))}
        </div>

        <div className="scroll" style={{flex:1, overflow:'auto', padding:'0 36px 40px'}}>
          <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(220px, 1fr))', gap:18}}>
            {showTutorial && <V2TutorialCard/>}
            {filtered.map(p => (
              <button key={p.id} onClick={()=>onOpenProject(p.raw)}
                title={`${window.location.origin}/?p=${encodeURIComponent(p.id)}`}
                style={{textAlign:'left', cursor:'pointer', background:'var(--paper)',
                  border:'1px solid var(--rule)', borderRadius:10, padding:0,
                  overflow:'hidden', display:'flex', flexDirection:'column'}}>
                <div style={{height:130, background:'var(--paper-2)', borderBottom:'1px solid var(--rule)',
                  display:'flex', alignItems:'center', justifyContent:'center', position:'relative'}}>
                  {p.fileCount > 0 ? <V2LivePreview/> : <V2DocStack/>}
                  {p.fileCount > 0 && p.scope === 'mine' && (
                    <span className="mono" style={{position:'absolute', top:8, right:8, fontSize:8.5,
                      padding:'2px 6px', background:'var(--accent)', color:'#fff', borderRadius:3, letterSpacing:'.08em'}}>LIVE</span>
                  )}
                  {p.scope === 'team' && (
                    <span className="mono" style={{position:'absolute', top:8, right:8, fontSize:8.5,
                      padding:'2px 7px', background:'var(--ink)', color:'#fff', borderRadius:3, letterSpacing:'.08em'}}>TEAM</span>
                  )}
                </div>
                <div style={{padding:'12px 14px 14px'}}>
                  <div style={{fontSize:13, fontWeight:600, marginBottom:3}}>{p.name}</div>
                  {p.scope === 'team' ? (
                    <div style={{display:'flex',alignItems:'center',gap:6,marginTop:5}}>
                      <div style={{width:18,height:18,borderRadius:9,background:'var(--accent)',color:'#fff',
                        display:'flex',alignItems:'center',justifyContent:'center',fontSize:9,fontWeight:600}}>
                        {(p.raw.client || '?').slice(0,1).toUpperCase()}
                      </div>
                      <span className="mono" style={{fontSize:9.5,color:'var(--muted)',letterSpacing:'.03em'}}>
                        team · {p.fileCount} files · {p.when}
                      </span>
                    </div>
                  ) : (
                    <div className="mono" style={{fontSize:10, color:'var(--muted)', letterSpacing:'.04em'}}>{p.fileCount} files · {p.sub}</div>
                  )}
                </div>
              </button>
            ))}
            {filtered.length===0 && !showTutorial && (
              <div style={{gridColumn:'1 / -1', textAlign:'center', padding:'60px 20px', color:'var(--muted)', fontSize:13}}>
                {recentTab === 'Team'
                  ? '팀원이 공유한 프로젝트가 없습니다.'
                  : (projects.length === 0 ? '아직 프로젝트가 없어요. 왼쪽에서 새 프로젝트를 만들어보세요.' : '검색 결과 없음')}
              </div>
            )}
          </div>
        </div>
      </main>
    </div>
  );
};

const V2TutorialCard = () => (
  <div style={{background:'#EAF1FB',border:'1px solid #D7E3F4',borderRadius:10,
    overflow:'hidden',display:'flex',flexDirection:'column',cursor:'pointer'}}>
    <div style={{height:130,display:'flex',alignItems:'center',justifyContent:'center',position:'relative'}}>
      <span style={{position:'absolute',top:8,right:10,color:'#5879A8',fontSize:13,cursor:'pointer'}}>×</span>
      <svg width="64" height="64" viewBox="0 0 64 64" fill="none">
        <ellipse cx="32" cy="50" rx="22" ry="3" fill="#C5D5EC" opacity=".5"/>
        <path d="M14 44 L14 30 Q14 28 16 28 L48 28 Q50 28 50 30 L50 44 Z" fill="#FFFFFF" stroke="#5879A8" strokeWidth="1.5"/>
        <path d="M14 44 L14 30 Q14 28 16 28 L32 28 L32 44 Z" fill="#F2F6FC" stroke="#5879A8" strokeWidth="1.5"/>
        <path d="M32 28 Q34 22 38 22 Q40 22 41 24 Q39 24 38 25 Q37 26 37 28" fill="#006747" stroke="#004D35" strokeWidth="1.2" strokeLinejoin="round"/>
        <path d="M40 22 Q41 19 43 19" stroke="#3D6B3D" strokeWidth="1.4" fill="none" strokeLinecap="round"/>
      </svg>
    </div>
    <div style={{padding:'12px 14px 14px'}}>
      <div style={{fontSize:13,fontWeight:600,color:'var(--ink)',marginBottom:3,lineHeight:1.35}}>
        Learn about<br/>Palette Mosaic
      </div>
      <div className="mono" style={{fontSize:10.5,color:'#3F6BB0',fontWeight:500,letterSpacing:'.02em'}}>Quick tutorial →</div>
    </div>
  </div>
);

const V2DocStack = () => (
  <svg width="60" height="60" viewBox="0 0 60 60">
    <rect x="14" y="20" width="32" height="28" rx="3" fill="#FBFAF6" stroke="#CCCCCC" strokeWidth="1.2"/>
    <rect x="11" y="16" width="32" height="28" rx="3" fill="#FFFFFF" stroke="#CCCCCC" strokeWidth="1.2"/>
    <line x1="16" y1="22" x2="36" y2="22" stroke="#E0DCD4" strokeWidth="1.2"/>
    <line x1="16" y1="27" x2="32" y2="27" stroke="#E0DCD4" strokeWidth="1.2"/>
    <line x1="16" y1="32" x2="34" y2="32" stroke="#E0DCD4" strokeWidth="1.2"/>
  </svg>
);

const V2LivePreview = () => (
  <div style={{width:'88%', height:90, background:'#fff', border:'1px solid #E0DCD4',
    borderRadius:6, overflow:'hidden', boxShadow:'0 1px 2px rgba(0,0,0,.04)',
    display:'grid', gridTemplateColumns:'18% 1fr 24%', gap:0}}>
    <div style={{background:'#FBFAF6', padding:4}}>
      <div style={{height:3,background:'rgba(0,103,71,.18)',borderRadius:1, marginBottom:2}}/>
      <div style={{height:2,background:'#E0DCD4',borderRadius:1, marginBottom:2,width:'70%'}}/>
    </div>
    <div style={{padding:4}}>
      <div style={{height:5,background:'#1A1A1A',borderRadius:1,width:'40%', marginBottom:3}}/>
      <div style={{display:'flex', gap:2, marginTop:2}}>
        <div style={{height:8,flex:1,background:'rgba(0,103,71,.18)',borderRadius:1}}/>
        <div style={{height:8,flex:1,background:'rgba(255,182,0,.22)',borderRadius:1}}/>
        <div style={{height:8,flex:1,background:'rgba(0,103,71,.10)',borderRadius:1}}/>
      </div>
    </div>
    <div style={{background:'#FBFAF6', padding:4}}>
      <div style={{display:'flex',flexWrap:'wrap',gap:1}}>
        {[0,1,2,3,4,5].map(i=>(<div key={i} style={{height:5, width: 8+i*2, background:'rgba(0,103,71,.16)',borderRadius:2}}/>))}
      </div>
    </div>
  </div>
);

window.V2HomeStage = V2HomeStage;
