// Scheduling demo ، publish calendar + tasks calendar, monthly/weekly, filters, drag from pool.

const { useState: useStateS, useMemo: useMemoS } = React;

// Helpers
const PF_DAY_LABELS = ['أحد','اثنين','ثلاثاء','أربعاء','خميس','جمعة','سبت'];
const PF_WEEK_DAYS = 28;

// Avatar pill
function PFAvatar({ user, size = 18 }) {
  if (!user) return null;
  return (
    <span style={{
      width:size, height:size, borderRadius:9999,
      background:user.color, color:'white',
      display:'inline-flex', alignItems:'center', justifyContent:'center',
      font:`700 ${Math.max(9, size*0.55)}px/1 var(--font-arabic)`,
      flex:'0 0 auto',
    }}>{user.initials}</span>
  );
}
window.PFAvatar = PFAvatar;

function SchedulingDemo() {
  const [tab, setTab] = useStateS('publish'); // 'publish' | 'tasks'
  const [view, setView] = useStateS('monthly'); // 'monthly' | 'weekly'
  const [ideas, setIdeas] = useStateS(window.PF_IDEAS_INIT.map(i => ({ ...i })));
  const [tasks] = useStateS(window.PF_TASKS_INIT);
  const [toast, setToast] = useStateS(null);
  const [dragId, setDragId] = useStateS(null);

  // Filters
  const [fPlatform, setFPlatform] = useStateS('all');
  const [fAccount,  setFAccount]  = useStateS('all');
  const [fTaskType, setFTaskType] = useStateS('all');
  const [fAssignee, setFAssignee] = useStateS('all');

  const flash = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(null), 1600);
  };

  const accountOf = (id) => window.PF_ACCOUNTS.find(a => a.id === id);
  const platformOf = (id) => window.PF_PLATFORMS.find(p => p.id === id);
  const userOf = (id) => window.PF_TEAM.find(u => u.id === id);
  const taskTypeOf = (id) => window.PF_TASK_TYPES.find(t => t.id === id);
  const ideaOf = (id) => ideas.find(i => i.id === id);

  // Filter ideas (publish tab)
  const filteredIdeas = useMemoS(() => ideas.filter(i =>
    (fPlatform === 'all' || i.platform === fPlatform) &&
    (fAccount  === 'all' || i.account  === fAccount)
  ), [ideas, fPlatform, fAccount]);

  // Filter tasks (tasks tab) ، also respect platform via parent idea
  const filteredTasks = useMemoS(() => tasks.filter(t => {
    const idea = ideaOf(t.idea);
    if (!idea) return false;
    if (fPlatform !== 'all' && idea.platform !== fPlatform) return false;
    if (fTaskType !== 'all' && t.type !== fTaskType) return false;
    if (fAssignee !== 'all' && t.assignee !== fAssignee) return false;
    return true;
  }), [tasks, ideas, fPlatform, fTaskType, fAssignee]);

  // Pool: ideas with no publish_date AND status === pool (publish tab) ، show always (drag source)
  const pool = useMemoS(() => ideas.filter(i => i.publish_date == null), [ideas]);

  // Drop a pool idea onto a day
  const onDropDay = (day) => {
    if (!dragId) return;
    setIdeas(arr => arr.map(i => i.id === dragId ? { ...i, publish_date: day } : i));
    flash('جدولت الفكرة');
    setDragId(null);
  };

  const onClickEmptyDay = (day, hasItems) => {
    if (hasItems) return;
    flash('اسحب فكرة من الـpool');
  };

  // Build day grid
  const days = view === 'monthly' ? 28 : 7;
  // For weekly we show days 0..6 but with a clearer row layout
  const daysArr = Array.from({ length: days }, (_, i) => i);

  // Compute items for each day
  const itemsForDay = (d) => {
    if (tab === 'publish') {
      return filteredIdeas.filter(i => i.publish_date === d);
    } else {
      return filteredTasks.filter(t => t.day === d);
    }
  };

  // Filter row
  const Select = ({ value, onChange, options, icon }) => (
    <label style={{
      display:'inline-flex', alignItems:'center', gap:6,
      padding:'6px 10px', borderRadius:8,
      border:'1px solid var(--border-default)', background:'var(--white)',
      font:'500 12px/1 var(--font-arabic)', color:'var(--fg-2)', cursor:'pointer',
    }}>
      {icon && <span style={{color:'var(--fg-4)'}}>{icon}</span>}
      <select value={value} onChange={(e) => onChange(e.target.value)}
        style={{border:0, background:'transparent', outline:'none', font:'inherit', color:'inherit', cursor:'pointer'}}>
        {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
    </label>
  );

  const platformOpts = [{ value:'all', label:'كل المنصات' }].concat(window.PF_PLATFORMS.map(p => ({ value:p.id, label:`${p.emoji} ${p.label}` })));
  const accountOpts = [{ value:'all', label:'كل الحسابات' }].concat(window.PF_ACCOUNTS.map(a => ({ value:a.id, label:a.label })));
  const taskTypeOpts = [{ value:'all', label:'كل المهام' }].concat(window.PF_TASK_TYPES.map(t => ({ value:t.id, label:`${t.emoji} ${t.label}` })));
  const assigneeOpts = [{ value:'all', label:'كل الفريق' }].concat(window.PF_TEAM.map(u => ({ value:u.id, label:u.name })));

  // Idea card on calendar (publish tab)
  const PublishCard = ({ idea }) => {
    const plat = platformOf(idea.platform);
    return (
      <div style={{
        background:'var(--white)',
        border:'1px solid var(--border-default)',
        borderInlineStart:`3px solid var(--stage-${window.PF_PLATFORM_COLOR[idea.platform] || 'indigo'}-bar)`,
        borderRadius:6, padding:'4px 6px',
        font:'600 10.5px/1.3 var(--font-arabic)', color:'var(--fg-1)',
        display:'flex', alignItems:'center', gap:4,
        boxShadow:'var(--shadow-sm)',
        overflow:'hidden',
      }} title={idea.title}>
        <span style={{flex:'0 0 auto', fontSize:11}}>{plat ? plat.emoji : ''}</span>
        <span style={{whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', flex:1, minWidth:0}}>{idea.title}</span>
      </div>
    );
  };

  // Task card on calendar (tasks tab)
  const TaskCard = ({ task }) => {
    const idea = ideaOf(task.idea);
    const type = taskTypeOf(task.type);
    const user = userOf(task.assignee);
    return (
      <div style={{
        background:'var(--white)',
        border:'1px solid var(--border-default)',
        borderInlineStart:`3px solid ${user ? user.color : 'var(--indigo-500)'}`,
        borderRadius:6, padding:'5px 6px',
        font:'600 10.5px/1.3 var(--font-arabic)', color:'var(--fg-1)',
        display:'flex', flexDirection:'column', gap:3,
        boxShadow:'var(--shadow-sm)',
        overflow:'hidden',
      }} title={`${type ? type.label : ''} ، ${idea ? idea.title : ''}`}>
        <span style={{display:'flex', alignItems:'center', gap:4}}>
          <span style={{fontSize:11}}>{type ? type.emoji : ''}</span>
          <span style={{font:'700 10.5px/1.2 var(--font-arabic)', color:'var(--fg-1)'}}>{type ? type.label : ''}</span>
        </span>
        <span style={{font:'500 10px/1.3 var(--font-arabic)', color:'var(--fg-3)',
          whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{idea ? idea.title : ''}</span>
        <span style={{display:'flex', alignItems:'center', gap:4}}>
          <PFAvatar user={user} size={14}/>
          <span style={{font:'500 9.5px/1 var(--font-arabic)', color:'var(--fg-3)'}}>{user ? user.name : ''}</span>
        </span>
      </div>
    );
  };

  // Day cell
  const DayCell = ({ d }) => {
    const items = itemsForDay(d);
    const hasItems = items.length > 0;
    return (
      <div
        onDragOver={(e) => { if (tab === 'publish' && dragId) e.preventDefault(); }}
        onDrop={() => tab === 'publish' && onDropDay(d)}
        onClick={() => onClickEmptyDay(d, hasItems)}
        style={{
          background:'var(--white)',
          border:'1px solid var(--border-default)',
          borderRadius:8, padding:6,
          minHeight: view === 'monthly' ? 78 : 130,
          display:'flex', flexDirection:'column', gap:4,
          cursor: tab === 'publish' ? 'copy' : 'default',
          position:'relative',
        }}>
        <div style={{
          font:'700 10.5px/1 var(--font-sans)', color:'var(--fg-3)',
          display:'flex', alignItems:'center', gap:4,
        }}>
          <span style={{fontVariantNumeric:'tabular-nums'}}>{d + 1}</span>
        </div>
        <div style={{display:'flex', flexDirection:'column', gap:3, flex:1}}>
          {tab === 'publish'
            ? items.map(i => <PublishCard key={i.id} idea={i}/>)
            : items.map(t => <TaskCard key={t.id} task={t}/>)}
        </div>
      </div>
    );
  };

  return (
    <div className="demo-shell">
      <div className="demo-chrome">
        <span className="dots"><i/><i/><i/></span>
        <span className="label">mazbat.app · الجدولة</span>
        <span className="demo-tag">تجربة حية</span>
      </div>
      <div style={{padding:'20px 22px', background:'var(--bg-app)', position:'relative'}}>
        {toast && <div className="demo-toast"><Check size={14}/> {toast}</div>}

        {/* Top tabs */}
        <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:14, flexWrap:'wrap'}}>
          <div style={{display:'inline-flex', gap:2, padding:3, background:'var(--slate-100)', borderRadius:'var(--radius-10)'}}>
            {[
              { id:'publish', label:'جدول النشر', icon:<Calendar size={12}/> },
              { id:'tasks',   label:'جدول المهام', icon:<ListChecks size={12}/> },
            ].map(t => {
              const active = tab === t.id;
              return (
                <button key={t.id} onClick={() => setTab(t.id)}
                  style={{
                    display:'inline-flex', alignItems:'center', gap:6,
                    padding:'7px 14px', borderRadius:'var(--radius-10)',
                    border: active ? '1px solid var(--indigo-200)' : '1px solid transparent',
                    background: active ? 'var(--white)' : 'transparent',
                    color: active ? 'var(--indigo-700)' : 'var(--fg-2)',
                    font: active ? '700 12.5px/1 var(--font-arabic)' : '600 12.5px/1 var(--font-arabic)',
                    cursor:'pointer', boxShadow: active ? 'var(--shadow-tab-active)' : 'none',
                  }}>
                  {t.icon} {t.label}
                </button>
              );
            })}
          </div>

          <span style={{flex:1}}/>

          {/* Monthly / Weekly */}
          <div style={{display:'inline-flex', gap:0, padding:0,
            border:'1px solid var(--border-default)', borderRadius:8, background:'var(--white)',
          }}>
            {[{id:'monthly',label:'شهري'},{id:'weekly',label:'أسبوعي'}].map(v => {
              const active = view === v.id;
              return (
                <button key={v.id} onClick={() => setView(v.id)}
                  style={{
                    padding:'7px 14px', border:0,
                    background: active ? 'var(--indigo-50)' : 'transparent',
                    color: active ? 'var(--indigo-700)' : 'var(--fg-2)',
                    font: active ? '700 12px/1 var(--font-arabic)' : '600 12px/1 var(--font-arabic)',
                    cursor:'pointer',
                  }}>{v.label}</button>
              );
            })}
          </div>
        </div>

        {/* Filters */}
        <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:14, flexWrap:'wrap'}}>
          <span style={{font:'600 11px/1 var(--font-arabic)', color:'var(--fg-3)', display:'inline-flex', alignItems:'center', gap:5}}>
            <Filter size={12}/> فلاتر:
          </span>
          <Select value={fPlatform} onChange={setFPlatform} options={platformOpts}/>
          {tab === 'publish' && <Select value={fAccount} onChange={setFAccount} options={accountOpts}/>}
          {tab === 'tasks' && <Select value={fTaskType} onChange={setFTaskType} options={taskTypeOpts}/>}
          {tab === 'tasks' && <Select value={fAssignee} onChange={setFAssignee} options={assigneeOpts}/>}
        </div>

        {/* Pool ، drag source (publish tab only) */}
        {tab === 'publish' && pool.length > 0 && (
          <div style={{
            background:'var(--white)', border:'1px dashed var(--border-strong)',
            borderRadius:'var(--radius-xl)', padding:'10px 12px', marginBottom:14,
            display:'flex', alignItems:'center', gap:10, flexWrap:'wrap',
          }}>
            <span style={{font:'700 11px/1 var(--font-arabic)', color:'var(--fg-2)', flex:'0 0 auto', display:'inline-flex', alignItems:'center', gap:5}}>
              <Inbox size={12}/> أفكار بدون تاريخ ({pool.length}) ، اسحب للجدول
            </span>
            <div style={{display:'flex', gap:6, flexWrap:'wrap', flex:1}}>
              {pool.map(i => {
                const plat = platformOf(i.platform);
                return (
                  <div key={i.id}
                    draggable
                    onDragStart={() => setDragId(i.id)}
                    onDragEnd={() => setDragId(null)}
                    style={{
                      background:'var(--white)',
                      border:'1px solid var(--border-default)',
                      borderInlineStart:`3px solid var(--stage-${window.PF_PLATFORM_COLOR[i.platform] || 'indigo'}-bar)`,
                      borderRadius:6, padding:'5px 9px',
                      font:'600 11px/1.2 var(--font-arabic)', color:'var(--fg-1)',
                      display:'inline-flex', alignItems:'center', gap:5,
                      cursor:'grab', boxShadow:'var(--shadow-sm)',
                      opacity: dragId === i.id ? 0.4 : 1,
                    }}>
                    <span style={{fontSize:11}}>{plat ? plat.emoji : ''}</span>
                    <span>{i.title}</span>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* Calendar grid */}
        {view === 'monthly' ? (
          <div>
            <div style={{display:'grid', gridTemplateColumns:'repeat(7, 1fr)', gap:6, marginBottom:6}}>
              {PF_DAY_LABELS.map(d => (
                <div key={d} style={{font:'700 11px/1 var(--font-arabic)', color:'var(--fg-3)', textAlign:'center', padding:'6px 0'}}>
                  {d}
                </div>
              ))}
            </div>
            <div style={{display:'grid', gridTemplateColumns:'repeat(7, 1fr)', gap:6}}>
              {daysArr.map(d => <DayCell key={d} d={d}/>)}
            </div>
          </div>
        ) : (
          <div>
            <div style={{display:'grid', gridTemplateColumns:'repeat(7, 1fr)', gap:6, marginBottom:6}}>
              {PF_DAY_LABELS.map((d, i) => (
                <div key={d} style={{font:'700 11px/1 var(--font-arabic)', color:'var(--fg-3)', textAlign:'center', padding:'6px 0'}}>
                  {d} <span style={{color:'var(--fg-4)', fontWeight:500}}>{i+1}</span>
                </div>
              ))}
            </div>
            <div style={{display:'grid', gridTemplateColumns:'repeat(7, 1fr)', gap:6}}>
              {daysArr.map(d => <DayCell key={d} d={d}/>)}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function SchedulingDemoSection() {
  return (
    <section className="section" style={{background:'var(--white)'}}>
      <div className="container">
        <div className="eyebrow">الميزة الثالثة · الجدولة</div>
        <h2 className="section-title">رتب مهام فريقك بأبسط طريقة</h2>
        <p className="section-sub">جدولة النشر والمهام في تقويم واحد. اسحب فكرة من الـpool إلى أي يوم، طبق فلتر، وراقب فريقك يتحرك بانسجام.</p>
        <SchedulingDemo/>
      </div>
    </section>
  );
}

window.SchedulingDemoSection = SchedulingDemoSection;
