// BeHueman v2 — Shared components
const { useState, useEffect, Fragment } = React;

// ---------- Icons ----------
function I({ name, size = 16, sw = 1.6 }) {
  const props = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: sw, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (name) {
    case 'Home': return <svg {...props}><path d="M3 10.5L12 3l9 7.5V20a1 1 0 01-1 1h-5v-7h-6v7H4a1 1 0 01-1-1z"/></svg>;
    case 'Dashboard': return <svg {...props}><rect x="3" y="3" width="7" height="9" rx="1"/><rect x="14" y="3" width="7" height="5" rx="1"/><rect x="14" y="12" width="7" height="9" rx="1"/><rect x="3" y="16" width="7" height="5" rx="1"/></svg>;
    case 'Community': return <svg {...props}><circle cx="9" cy="8" r="3"/><circle cx="17" cy="9" r="2.5"/><path d="M3 19c0-3.3 2.7-6 6-6s6 2.7 6 6"/><path d="M14.5 19c0-2.5 2-4.5 4.5-4.5"/></svg>;
    case 'Education': return <svg {...props}><path d="M2 8l10-5 10 5-10 5z"/><path d="M6 10v6c0 1.5 3 3 6 3s6-1.5 6-3v-6"/></svg>;
    case 'Fun': return <svg {...props}><circle cx="12" cy="12" r="9"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><circle cx="9" cy="10" r="0.5" fill="currentColor"/><circle cx="15" cy="10" r="0.5" fill="currentColor"/></svg>;
    case 'Library': return <svg {...props}><rect x="4" y="3" width="3" height="18" rx="1"/><rect x="9" y="3" width="3" height="18" rx="1"/><path d="M14 5l3-1 3 17-3 1z"/></svg>;
    case 'User': return <svg {...props}><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4.4 3.6-8 8-8s8 3.6 8 8"/></svg>;
    case 'Bell': return <svg {...props}><path d="M6 8a6 6 0 0112 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10 21a2 2 0 004 0"/></svg>;
    case 'Settings': return <svg {...props}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 00.3 1.8l.1.1a2 2 0 01-2.8 2.8l-.1-.1a1.7 1.7 0 00-1.8-.3 1.7 1.7 0 00-1 1.5V21a2 2 0 01-4 0v-.1a1.7 1.7 0 00-1-1.5 1.7 1.7 0 00-1.8.3l-.1.1a2 2 0 11-2.8-2.8l.1-.1a1.7 1.7 0 00.3-1.8 1.7 1.7 0 00-1.5-1H3a2 2 0 010-4h.1a1.7 1.7 0 001.5-1 1.7 1.7 0 00-.3-1.8l-.1-.1a2 2 0 012.8-2.8l.1.1a1.7 1.7 0 001.8.3H9a1.7 1.7 0 001-1.5V3a2 2 0 014 0v.1a1.7 1.7 0 001 1.5 1.7 1.7 0 001.8-.3l.1-.1a2 2 0 012.8 2.8l-.1.1a1.7 1.7 0 00-.3 1.8V9a1.7 1.7 0 001.5 1H21a2 2 0 010 4h-.1a1.7 1.7 0 00-1.5 1z"/></svg>;
    case 'Search': return <svg {...props}><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>;
    case 'Plus': return <svg {...props}><path d="M12 5v14M5 12h14"/></svg>;
    case 'Calendar': return <svg {...props}><rect x="3" y="5" width="18" height="16" rx="1"/><path d="M3 10h18M8 3v4M16 3v4"/></svg>;
    case 'MapPin': return <svg {...props}><path d="M12 21s7-7 7-12a7 7 0 10-14 0c0 5 7 12 7 12z"/><circle cx="12" cy="9" r="2.5"/></svg>;
    case 'Users': return <svg {...props}><circle cx="9" cy="8" r="3"/><path d="M3 19c0-3.3 2.7-6 6-6s6 2.7 6 6"/><circle cx="17" cy="9" r="2.5"/><path d="M21 18c0-2-1-4-4-4"/></svg>;
    case 'Sparkle': return <svg {...props}><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2 2M16.4 16.4l2 2M5.6 18.4l2-2M16.4 7.6l2-2"/></svg>;
    case 'Heart': return <svg {...props}><path d="M12 21s-7-4.5-9.5-9.5C.8 8 3 4 7 4c2 0 3.5 1 5 3 1.5-2 3-3 5-3 4 0 6.2 4 4.5 7.5C19 16.5 12 21 12 21z"/></svg>;
    case 'Comment': return <svg {...props}><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg>;
    case 'Bookmark': return <svg {...props}><path d="M19 21l-7-5-7 5V5a2 2 0 012-2h10a2 2 0 012 2z"/></svg>;
    case 'Share': return <svg {...props}><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 13.5l6.8 4M15.4 6.5l-6.8 4"/></svg>;
    // Share external — arrow leaving box
    case 'ShareExternal': return <svg {...props}><path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"/><path d="M15 3h6v6"/><path d="M10 14L21 3"/></svg>;
    // Repost — curved arrow (boost/repost)
    case 'Repost': return <svg {...props}><path d="M17 1l4 4-4 4"/><path d="M3 11V9a4 4 0 014-4h14"/><path d="M7 23l-4-4 4-4"/><path d="M21 13v2a4 4 0 01-4 4H3"/></svg>;
    case 'More': return <svg {...props}><circle cx="12" cy="12" r="1" fill="currentColor"/><circle cx="6" cy="12" r="1" fill="currentColor"/><circle cx="18" cy="12" r="1" fill="currentColor"/></svg>;
    case 'Chevron': return <svg {...props}><path d="M9 18l6-6-6-6"/></svg>;
    case 'ChevronDown': return <svg {...props}><path d="M6 9l6 6 6-6"/></svg>;
    case 'Check': return <svg {...props}><path d="M5 12l5 5L20 6"/></svg>;
    case 'Verified': return <svg {...props} fill="currentColor" stroke="none"><path d="M12 2l2.4 2 3.1-.4 1.3 2.9 2.8 1.4-.4 3.1 2 2.4-2 2.4.4 3.1-2.8 1.4-1.3 2.9-3.1-.4L12 22l-2.4-2-3.1.4L5.2 17.5 2.4 16.1l.4-3.1-2-2.4 2-2.4-.4-3.1L5.2 3.7 6.5.8 9.6 2.4z M10.5 15.5L7 12l1.4-1.4 2.1 2.1L15.6 8 17 9.4z"/></svg>;
    case 'Shield': return <svg {...props}><path d="M12 3l8 3v6c0 5-4 8-8 9-4-1-8-4-8-9V6z"/></svg>;
    case 'Sliders': return <svg {...props}><path d="M4 6h12M20 6h-2M4 12h2M10 12h10M4 18h10M16 18h4"/><circle cx="18" cy="6" r="2"/><circle cx="8" cy="12" r="2"/><circle cx="13" cy="18" r="2"/></svg>;
    case 'Filter': return <svg {...props}><path d="M3 5h18l-7 9v6l-4-2v-4z"/></svg>;
    case 'Send': return <svg {...props}><path d="M22 2L11 13M22 2l-7 20-4-9-9-4z"/></svg>;
    case 'Link': return <svg {...props}><path d="M10 13a5 5 0 007.5.5l2-2a5 5 0 00-7-7l-1 1"/><path d="M14 11a5 5 0 00-7.5-.5l-2 2a5 5 0 007 7l1-1"/></svg>;
    case 'X': return <svg {...props}><path d="M18 6L6 18M6 6l12 12"/></svg>;
    case 'Eye': return <svg {...props}><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></svg>;
    case 'EyeOff': return <svg {...props}><path d="M17.9 17.9A10 10 0 0112 19c-5.5 0-10-7-10-7a17.8 17.8 0 015.1-5.9M9.9 4.2A9.8 9.8 0 0112 4c5.5 0 10 7 10 7a17.8 17.8 0 01-2.3 3.1M1 1l22 22"/><circle cx="12" cy="12" r="3" style={{display:'none'}}/></svg>;
    case 'Grip': return <svg {...props}><circle cx="9" cy="6" r="0.8" fill="currentColor"/><circle cx="15" cy="6" r="0.8" fill="currentColor"/><circle cx="9" cy="12" r="0.8" fill="currentColor"/><circle cx="15" cy="12" r="0.8" fill="currentColor"/><circle cx="9" cy="18" r="0.8" fill="currentColor"/><circle cx="15" cy="18" r="0.8" fill="currentColor"/></svg>;
    case 'Globe': return <svg {...props}><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 010 18M12 3a14 14 0 000 18"/></svg>;
    case 'Briefcase': return <svg {...props}><rect x="3" y="7" width="18" height="13" rx="2"/><path d="M8 7V5a2 2 0 012-2h4a2 2 0 012 2v2M3 13h18"/></svg>;
    case 'Award': return <svg {...props}><circle cx="12" cy="8" r="6"/><path d="M8.6 14.5L7 21l5-3 5 3-1.6-6.5"/></svg>;
    case 'Pencil': return <svg {...props}><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.1 2.1 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>;
    case 'Layers': return <svg {...props}><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg>;
    case 'Music': return <svg {...props}><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>;
    case 'Plane': return <svg {...props}><path d="M22 2L11 13"/><path d="M22 2L15 22l-4-9-9-4 20-7z"/></svg>;
    case 'Smile': return <svg {...props}><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg>;
    case 'Zap': return <svg {...props}><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>;
    case 'Package': return <svg {...props}><line x1="16.5" y1="9.4" x2="7.5" y2="4.2"/><path d="M21 16V8a2 2 0 00-1-1.7l-7-4a2 2 0 00-2 0l-7 4A2 2 0 002 8v8a2 2 0 001 1.7l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/><polyline points="3.3 7 12 12 20.7 7"/><line x1="12" y1="22" x2="12" y2="12"/></svg>;
    case 'ArrowLeft': return <svg {...props}><path d="M19 12H5M12 19l-7-7 7-7"/></svg>;
    case 'Image': return <svg {...props}><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>;
    default: return <svg {...props}><circle cx="12" cy="12" r="9"/></svg>;
  }
}

// ---------- Avatar ----------
function Avatar({ author, size = 36, link = false }) {
  const a = typeof author === 'string' ? AppData.getAuthor(author) : author;
  const initials = a.name.split(' ').map(s => s[0]).slice(0,2).join('');
  const onClick = link ? (e) => { e.stopPropagation(); window.openDetail && window.openDetail('author', a); } : undefined;
  return (
    <div className={`avatar ${a.verified ? 'verified' : ''}`} onClick={onClick} style={{
      width: size, height: size,
      background: `linear-gradient(135deg, ${a.avatar[0]}, ${a.avatar[1]})`,
      fontSize: size * 0.36,
      cursor: link ? 'pointer' : 'default',
    }}>{initials}</div>
  );
}

function VerifiedBadge() {
  return (
    <span title="Verified" style={{display:'inline-flex', alignItems:'center', color: 'var(--accent)'}}>
      <I name="Verified" size={14}/>
    </span>
  );
}

// ---------- Toggle ----------
function Toggle({ on, onChange }) {
  return (
    <button className={`toggle ${on?'on':''}`} onClick={() => onChange(!on)} aria-pressed={on}/>
  );
}

// ---------- Page header ----------
function PageHeader({ eyebrow, title, subtitle, ff, action }) {
  return (
    <div className="page-header">
      <div className="row gap-12 mb-8" style={{justifyContent:'space-between', alignItems:'flex-start'}}>
        <div>
          <div className="page-eyebrow row gap-8" style={{alignItems:'center'}}>
            {eyebrow}
            {ff && <span className={`phase-ribbon ${ff.toLowerCase()}`}>{ff}</span>}
          </div>
          <h1 className="page-title">{title}</h1>
          {subtitle && <div className="page-sub">{subtitle}</div>}
        </div>
        {action && <div>{action}</div>}
      </div>
    </div>
  );
}

// ---------- Domain chip ----------
function DomainChip({ domainId, sub }) {
  const d = AppData.domains.find(x => x.id === domainId);
  if (!d) return null;
  return (
    <span className={`chip chip-hue-${d.id}`}>
      {d.label}{sub ? ` · ${sub}` : ''}
    </span>
  );
}

// ---------- Cover background ----------
const coverBg = (cols) => `linear-gradient(135deg, ${cols[0]}, ${cols[1]})`;

// ---------- Post Card v2 (4 reactions, 2 share types) ----------
function PostCard({ post, onOpenDetail }) {
  const a = AppData.getAuthor(post.authorId);
  const [reactions, setReactions] = useState(new Set());
  const [saved, setSaved] = useState(false);
  const [reposted, setReposted] = useState(false);

  const toggleReaction = (r) => {
    setReactions(prev => { const n = new Set(prev); n.has(r) ? n.delete(r) : n.add(r); return n; });
  };

  const REACTIONS = [
    { key: 'heart', emoji: '❤️', base: post.likes },
    { key: 'smile', emoji: '😊', base: Math.round((post.likes||0) * 0.38) },
    { key: 'idea',  emoji: '💡', base: Math.round((post.likes||0) * 0.19) },
    { key: 'spark', emoji: '✨', base: Math.round((post.likes||0) * 0.14) },
  ];

  const roleLabelMap = { autor: 'Autor', partner: 'Partner', member: 'Member' };

  const ctx = (e) => {
    if (!window.openContextMenu) return;
    openContextMenu(e, [
      { label: 'Skopiuj link', icon: 'Link', onClick: () => window.__app.pushToast('ok','Skopiowano','Link jest w schowku.') },
      { label: 'Zapisz do Biblioteki', icon: 'Bookmark', onClick: () => { setSaved(true); window.__app.pushToast('ok','Zapisano','Treść w Twojej Bibliotece.'); } },
      { label: 'Wycisz autora', icon: 'EyeOff', onClick: () => window.__app.pushToast('ok','Wyciszono','Posty od @'+a.handle+' nie będą się pokazywać.') },
      { label: 'Nieinteresujące', icon: 'X', onClick: () => window.__app.pushToast('ok','Zapamiętane','Pokażemy mniej takich postów.') },
      { label: 'Zgłoś post', icon: 'Shield', danger: true, onClick: () => window.openReport && openReport('post', post.id, `Post od ${a.name}`) },
      { label: 'Przekształć w wątek tematyczny', icon: 'Users', hint: 'Go Live', onClick: () => window.__app.pushToast('warn','Wkrótce','Dostępne po Go-Live.') },
    ]);
  };

  return (
    <div className="post">
      <div className="post-head">
        <Avatar author={a} size={40} link/>
        <div style={{flex:1, minWidth:0}}>
          <div className="row gap-4" style={{flexWrap:'wrap'}}>
            <span className="post-author" style={{cursor:'pointer'}} onClick={()=>window.openDetail && window.openDetail('author', a)}>{a.name}</span>
            {a.verified && <VerifiedBadge/>}
            <span className={`role-badge ${a.role}`}>{roleLabelMap[a.role] || a.role}</span>
            <span style={{color:'var(--ink-4)'}}>·</span>
            <span className="post-meta">@{a.handle}</span>
          </div>
          <div className="row gap-8" style={{marginTop:2}}>
            <DomainChip domainId={post.domain} sub={post.sub}/>
            <span className="post-meta">· {post.time}</span>
          </div>
        </div>
        <button className="icon-btn" style={{width:30, height:30, border:'none', background:'transparent'}} onClick={ctx}>
          <I name="More" size={16}/>
        </button>
      </div>

      <div className="post-body" style={{cursor: onOpenDetail ? 'pointer' : 'default'}}
           onClick={() => onOpenDetail && onOpenDetail(post)}>
        {post.body.split('\n\n').map((p,i) => <p key={i} style={{margin:'0 0 10px 0'}}>{p}</p>)}
      </div>

      {post.rec && (
        <div className="rec">
          <div className="rec-cover" style={{background: coverBg(post.rec.cover)}}/>
          <div className="rec-content">
            <span className="rec-source">{post.rec.type} · <b>Drop-a-Find</b></span>
            <span className="rec-title">{post.rec.title}</span>
            <span className="rec-author">{post.rec.author}</span>
            <button className="btn btn-soft btn-sm" style={{alignSelf:'flex-start', marginTop:6}}>
              <I name="Bookmark" size={12}/> Zapisz w Bibliotece
            </button>
          </div>
        </div>
      )}

      {/* Actions row v2 */}
      <div className="post-actions-v2">
        {/* 4 reaction toggles — always visible */}
        <div className="reactions-bar">
          {REACTIONS.map(r => (
            <button key={r.key} className={`reaction-btn ${reactions.has(r.key) ? 'active' : ''}`}
                    onClick={() => toggleReaction(r.key)}>
              <span className="reaction-emoji">{r.emoji}</span>
              <span className="reaction-count">{r.base + (reactions.has(r.key) ? 1 : 0)}</span>
            </button>
          ))}
        </div>

        {/* Comments */}
        <button className="post-action-share" style={{marginLeft:4}}>
          <I name="Comment" size={15}/>&nbsp;<span style={{fontSize:12}}>{post.comments}</span>
        </button>

        <div className="post-actions-spacer"/>

        {/* Share external — with watermark BeHueman */}
        <button className="post-action-share" title="Udostępnij poza platformą (z watermarkiem BeHueman)"
                onClick={() => window.__app.pushToast('ok','Udostępnianie','Otwarto okno udostępniania z watermarkiem BeHueman.')}>
          <I name="ShareExternal" size={15}/>
        </button>

        {/* Repost — boost to own wall */}
        <button className={`post-action-share ${reposted ? 'active' : ''}`}
                title="Podbij — pojawi się na Twoim wallu"
                onClick={() => { setReposted(!reposted); if (!reposted) window.__app.pushToast('ok','Podbito','Post pojawił się na Twoim wallu.'); }}>
          <I name="Repost" size={15}/>
        </button>

        {/* Bookmark */}
        <button className={`post-action-share ${saved ? 'active' : ''}`}
                title="Zapisz do Biblioteki"
                onClick={() => { setSaved(!saved); if (!saved) window.__app.pushToast('ok','Zapisano w Bibliotece','Kliknij ikonę zakładki w górnym pasku, by zobaczyć.'); }}>
          <I name="Bookmark" size={15}/>
        </button>
      </div>
    </div>
  );
}

// ---------- Tile ----------
function Tile({ tile, onClick }) {
  return (
    <div className="tile" onClick={onClick} style={{cursor: onClick ? 'pointer' : 'default'}}>
      <div className="tile-cover" style={{background: coverBg(tile.cover)}}>
        <span className="tile-type">{tile.type}</span>
      </div>
      <div className="tile-meta">
        <div className="tile-title">{tile.title}</div>
        <div className="tile-author">{tile.author}</div>
      </div>
    </div>
  );
}

// ---------- Row Strip (horizontal scroll) ----------
function RowStrip({ eyebrow, title, items, onSeeAll }) {
  return (
    <div className="row-strip">
      <div className="row-strip-head">
        <div>
          <div className="row-strip-eyebrow">{eyebrow}</div>
          <div className="row-strip-title">{title}</div>
        </div>
        <button className="btn btn-soft btn-sm" onClick={onSeeAll}>
          Wszystkie <I name="Chevron" size={12}/>
        </button>
      </div>
      <div className="row-strip-track">
        {items.map(t => <Tile key={t.id} tile={t} onClick={() => window.openDetail && window.openDetail('course', t)}/>)}
      </div>
    </div>
  );
}

// ---------- Right rail (community sidebar) ----------
function RightRail({ onOpenAuthor }) {
  return (
    <div className="col gap-16" style={{position:'sticky', top:80}}>
      <div className="card" style={{padding:18}}>
        <div className="section-eyebrow mb-12">Zasady wspólnoty</div>
        <ul style={{listStyle:'none', padding:0, margin:0, display:'flex', flexDirection:'column', gap:8, fontSize:12.5, color:'var(--ink-2)'}}>
          <li className="row gap-8"><I name="Check" size={13}/> Nie hejtujemy.</li>
          <li className="row gap-8"><I name="Check" size={13}/> Szanujemy każdą perspektywę.</li>
          <li className="row gap-8"><I name="Check" size={13}/> Bez gwiazdek — rozmawiamy.</li>
          <li className="row gap-8"><I name="Check" size={13}/> Współpracujemy zamiast rywalizować.</li>
        </ul>
      </div>
      <div className="card" style={{padding:18}}>
        <div className="section-eyebrow mb-12">Polecani autorzy</div>
        {AppData.authors.filter(a => a.role !== 'member').slice(0,4).map((a,i) => (
          <div key={a.id} className="row gap-12" style={{padding:'10px 0', borderTop: i?'1px solid var(--line-soft)':'', cursor:'pointer'}} onClick={()=>onOpenAuthor && onOpenAuthor(a)}>
            <Avatar author={a} size={36}/>
            <div style={{flex:1, minWidth:0}}>
              <div className="row gap-4"><span style={{fontSize:13, fontWeight:600}}>{a.name}</span>{a.verified && <VerifiedBadge/>}</div>
              <div className="muted" style={{fontSize:11.5}}>{a.followers} obserwujących</div>
            </div>
            <button className="btn btn-ghost btn-sm">Obserwuj</button>
          </div>
        ))}
      </div>
      <div className="card" style={{padding:18, background:'color-mix(in oklab, var(--hue-amber) 14%, var(--bg-elev))'}}>
        <div className="section-eyebrow">Dlaczego tu jesteśmy</div>
        <div style={{fontFamily:'var(--font-serif)', fontSize:18, lineHeight:1.3, marginTop:8, fontWeight:500}}>"Bądź <i>hue</i>man — wnoś swój odcień, nie kopiuj cudzych."</div>
      </div>
    </div>
  );
}

// ---------- Modal ----------
function Modal({ title, onClose, children, footer, wide }) {
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className={`modal ${wide?'modal-wide':''}`} onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <h2 className="modal-title">{title}</h2>
          <button className="icon-btn" style={{border:'none', background:'transparent'}} onClick={onClose}><I name="X" size={16}/></button>
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-foot">{footer}</div>}
      </div>
    </div>
  );
}

Object.assign(window, {
  I, Avatar, VerifiedBadge, Toggle, PageHeader, DomainChip, PostCard,
  Tile, RowStrip, RightRail, Modal, coverBg,
  useState, useEffect, Fragment,
});
Object.assign(window, AppData);
