// Social Media Content Calendar
const CCIcons = window.Icons;
const { toDateKey: ccKey, parseDateKey: ccParse, relativeDate: ccRel } = window.PMStore;

const PLATFORMS = [
  { id: 'instagram', label: 'Instagram',   short: 'IG', color: '#E1306C', icon: 'Instagram' },
  { id: 'facebook',  label: 'Facebook',    short: 'FB', color: '#1877F2', icon: 'Facebook'  },
  { id: 'linkedin',  label: 'LinkedIn',    short: 'LI', color: '#0A66C2', icon: 'Linkedin'  },
  { id: 'tiktok',    label: 'TikTok',      short: 'TT', color: '#010101', icon: 'TikTok'    },
  { id: 'twitter',   label: 'X / Twitter', short: 'TW', color: '#1DA1F2', icon: 'Twitter'   },
  { id: 'youtube',   label: 'YouTube',     short: 'YT', color: '#FF0000', icon: 'Youtube'   },
];

const CONTENT_TYPES = [
  { id: 'post',      label: 'Gönderi',  emoji: '📷' },
  { id: 'story',     label: 'Hikaye',   emoji: '⚡' },
  { id: 'reel',      label: 'Reel',     emoji: '🎬' },
  { id: 'video',     label: 'Video',    emoji: '▶️' },
  { id: 'carousel',  label: 'Carousel', emoji: '🔄' },
  { id: 'article',   label: 'Makale',   emoji: '📝' },
];

const CONTENT_STATUSES = [
  { id: 'brief',         label: 'Brief',          color: '#94a3b8' },
  { id: 'production',    label: 'Üretimde',       color: '#3b82f6' },
  { id: 'review',        label: 'İncelemede',     color: '#a855f7' },
  { id: 'client_review', label: 'Müşteri Onayı', color: '#f59e0b' },
  { id: 'approved',      label: 'Onaylandı',      color: '#22c55e' },
  { id: 'scheduled',     label: 'Zamanlandı',     color: '#6366f1' },
  { id: 'published',     label: 'Yayınlandı',     color: '#ff601f' },
];

const DAYS_TR   = ['Pzt', 'Sal', 'Çar', 'Per', 'Cum', 'Cmt', 'Paz'];
const MONTHS_TR = ['Ocak','Şubat','Mart','Nisan','Mayıs','Haziran','Temmuz','Ağustos','Eylül','Ekim','Kasım','Aralık'];

function d0(date) { const d = new Date(date); d.setHours(0,0,0,0); return d; }

function ContentCalendar({ state, onSelectTask, onAddTask, onUpdateTask }) {
  const today = d0(new Date());
  const [year, setYear]         = React.useState(today.getFullYear());
  const [month, setMonth]       = React.useState(today.getMonth());
  const [pfFilter, setPF]       = React.useState('all');
  const [projFilter, setPJ]     = React.useState('all');
  const [viewMode, setVM]       = React.useState('month');
  const [createDate, setCD]     = React.useState(null);

  const prevMonth = () => month === 0 ? (setMonth(11), setYear(y => y-1)) : setMonth(m => m-1);
  const nextMonth = () => month === 11? (setMonth(0),  setYear(y => y+1)) : setMonth(m => m+1);
  const goToday   = () => { setYear(today.getFullYear()); setMonth(today.getMonth()); };

  const projById = Object.fromEntries((state.projects||[]).map(p => [p.id, p]));

  const contentTasks = (state.tasks||[]).filter(t =>
    t.platform && !t.archived &&
    (pfFilter   === 'all' || t.platform   === pfFilter) &&
    (projFilter === 'all' || t.projectId  === projFilter)
  );

  // Monthly grid
  const firstDay = new Date(year, month, 1);
  const lastDay  = new Date(year, month + 1, 0);
  const startDow = (firstDay.getDay() + 6) % 7;
  const cells = [];
  for (let i = 0; i < startDow; i++) cells.push(null);
  for (let d = 1; d <= lastDay.getDate(); d++) cells.push(new Date(year, month, d));

  const tasksByDate = {};
  contentTasks.forEach(t => {
    if (t.due) { (tasksByDate[t.due] = tasksByDate[t.due] || []).push(t); }
  });

  // Stats bar
  const monthStart = ccKey(new Date(year, month, 1));
  const monthEnd   = ccKey(new Date(year, month + 1, 0));
  const monthTasks = contentTasks.filter(t => t.due && t.due >= monthStart && t.due <= monthEnd);

  return (
    <div className="content cc-content">
      {/* ── Toolbar ─────────────────────────────────────────── */}
      <div className="cc-toolbar">
        <div className="cc-nav">
          <button className="icon-btn" onClick={prevMonth}><CCIcons.ChevronLeft size={16}/></button>
          <h2 className="cc-month-title">{MONTHS_TR[month]} {year}</h2>
          <button className="icon-btn" onClick={nextMonth}><CCIcons.ChevronRight size={16}/></button>
          <button className="btn btn-ghost btn-sm" onClick={goToday}>Bugün</button>
        </div>

        <div className="cc-right-tools">
          <div className="cc-platform-pills">
            <button className={`cc-ppill ${pfFilter==='all'?'active':''}`} onClick={() => setPF('all')}>Tümü</button>
            {PLATFORMS.map(p => (
              <button key={p.id}
                className={`cc-ppill ${pfFilter===p.id?'active':''}`}
                style={pfFilter===p.id ? {background: p.color, borderColor: p.color, color:'#fff'} : {}}
                onClick={() => setPF(pfFilter===p.id ? 'all' : p.id)}>
                {p.short}
              </button>
            ))}
          </div>
          <select className="select-control" value={projFilter} onChange={e => setPJ(e.target.value)}>
            <option value="all">Tüm Müşteriler</option>
            {(state.projects||[]).map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
          <div className="cc-view-tabs">
            {[{id:'month',label:'Aylık'},{id:'list',label:'Liste'},{id:'pipeline',label:'Pipeline'}].map(v => (
              <button key={v.id} className={`view-tab ${viewMode===v.id?'active':''}`} onClick={() => setVM(v.id)}>
                {v.label}
              </button>
            ))}
          </div>
          <button className="btn btn-primary btn-sm" onClick={() => setCD(ccKey(today))}>
            <CCIcons.Plus size={13}/> Yeni İçerik
          </button>
        </div>
      </div>

      {/* ── Ay özeti ────────────────────────────────────────── */}
      {monthTasks.length > 0 && (
        <div className="cc-stats-bar">
          <span className="cc-stats-total"><strong>{monthTasks.length}</strong> içerik</span>
          {PLATFORMS.filter(p => monthTasks.some(t => t.platform===p.id)).map(p => {
            const cnt = monthTasks.filter(t => t.platform===p.id).length;
            return (
              <span key={p.id} className="cc-stat-chip" style={{borderColor:p.color,color:p.color}}>
                {p.short} {cnt}
              </span>
            );
          })}
          <span className="cc-stats-sep" />
          {CONTENT_STATUSES.map(s => {
            const cnt = monthTasks.filter(t => (t.contentStatus||'brief')===s.id).length;
            if (!cnt) return null;
            return (
              <span key={s.id} className="cc-stat-chip" style={{borderColor:s.color,color:s.color}}>
                {s.label} {cnt}
              </span>
            );
          })}
        </div>
      )}

      {/* ── Görünümler ──────────────────────────────────────── */}
      {viewMode === 'month' && (
        <div className="cc-grid-wrap">
          <div className="cc-day-names">
            {DAYS_TR.map(d => <div key={d} className="cc-day-name">{d}</div>)}
          </div>
          <div className="cc-grid">
            {cells.map((date, i) => {
              if (!date) return <div key={`e${i}`} className="cc-cell cc-cell-empty"/>;
              const dk = ccKey(date);
              const dayTasks = tasksByDate[dk] || [];
              const isToday = date.getTime() === today.getTime();
              const isWeekend = date.getDay() === 0 || date.getDay() === 6;
              return (
                <div key={dk} className={`cc-cell ${isToday?'today':''} ${isWeekend?'weekend':''}`}>
                  <div className="cc-cell-hdr">
                    <span className={`cc-day-num ${isToday?'today':''}`}>{date.getDate()}</span>
                    <button className="cc-add-btn" onClick={() => setCD(dk)} title="İçerik ekle">
                      <CCIcons.Plus size={11}/>
                    </button>
                  </div>
                  <div className="cc-cell-body">
                    {dayTasks.slice(0,3).map(t => (
                      <ContentCard key={t.id} task={t} project={projById[t.projectId]} onClick={() => onSelectTask(t.id)}/>
                    ))}
                    {dayTasks.length > 3 && (
                      <div className="cc-more">+{dayTasks.length-3} daha</div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {viewMode === 'list' && (
        <ContentListView
          tasks={contentTasks}
          projById={projById}
          onSelectTask={onSelectTask}
          onNew={() => setCD(ccKey(today))}
          onUpdateTask={onUpdateTask}
        />
      )}

      {viewMode === 'pipeline' && (
        <ContentPipeline
          tasks={contentTasks}
          projById={projById}
          onSelectTask={onSelectTask}
          onUpdateTask={onUpdateTask}
          onNew={() => setCD(ccKey(today))}
        />
      )}

      {createDate && (
        <ContentCreateModal
          date={createDate}
          state={state}
          onSave={(data) => { onAddTask(data); setCD(null); }}
          onClose={() => setCD(null)}
        />
      )}
    </div>
  );
}

/* ── İçerik kartı (aylık grid için) ───────────────────────── */
function ContentCard({ task, project, onClick }) {
  const pf  = PLATFORMS.find(p => p.id === task.platform);
  const ct  = CONTENT_TYPES.find(c => c.id === task.contentType);
  const cs  = CONTENT_STATUSES.find(s => s.id === (task.contentStatus || 'brief'));
  return (
    <div className="cc-card" onClick={onClick} style={{borderLeftColor: pf?.color||'var(--border)'}}>
      <div className="cc-card-top">
        <span className="cc-pbadge" style={{background:pf?.color}}>{pf?.short}</span>
        {ct && <span className="cc-type-emoji">{ct.emoji}</span>}
        <span className="cc-sdot" style={{background:cs?.color}} title={cs?.label}/>
      </div>
      <div className="cc-card-title">{task.title}</div>
      {project && <div className="cc-card-client">{project.name}</div>}
    </div>
  );
}

/* ── Liste görünümü ────────────────────────────────────────── */
function ContentListView({ tasks, projById, onSelectTask, onNew, onUpdateTask }) {
  const sorted = [...tasks].sort((a,b) => (a.due||'9999').localeCompare(b.due||'9999'));

  // Group by week
  const groups = [];
  sorted.forEach(t => {
    const d = t.due ? ccParse(t.due) : null;
    const weekLabel = d ? getWeekLabel(d) : 'Tarihi Belirsiz';
    const last = groups[groups.length-1];
    if (last && last.label === weekLabel) last.tasks.push(t);
    else groups.push({ label: weekLabel, tasks: [t] });
  });

  return (
    <div className="cc-list-view">
      <div className="cc-list-topbar">
        <button className="btn btn-primary btn-sm" onClick={onNew}>
          <CCIcons.Plus size={13}/> Yeni İçerik
        </button>
      </div>
      {groups.length === 0 && (
        <div className="empty">
          <div className="empty-icon"><CCIcons.Calendar size={22}/></div>
          <div className="empty-title">İçerik yok</div>
          <div>Filtre değiştirin veya yeni içerik ekleyin.</div>
        </div>
      )}
      {groups.map(g => (
        <div key={g.label} className="cc-list-group">
          <div className="cc-list-group-hdr">{g.label} <span>{g.tasks.length}</span></div>
          {g.tasks.map(t => (
            <ContentListRow key={t.id} task={t} project={projById[t.projectId]}
              onClick={() => onSelectTask(t.id)}
              onStatusChange={(s) => onUpdateTask(t.id, { contentStatus: s })}
            />
          ))}
        </div>
      ))}
    </div>
  );
}

function ContentListRow({ task, project, onClick, onStatusChange }) {
  const pf = PLATFORMS.find(p => p.id === task.platform);
  const ct = CONTENT_TYPES.find(c => c.id === task.contentType);
  const cs = CONTENT_STATUSES.find(s => s.id === (task.contentStatus||'brief'));
  return (
    <div className="cc-list-row" onClick={onClick}>
      <span className="cc-pbadge" style={{background:pf?.color}}>{pf?.short}</span>
      <div className="cc-list-main">
        <div className="cc-list-title">{task.title}</div>
        <div className="cc-list-meta">
          {project && <><span className="project-dot" style={{background:project.color}}/><span>{project.name}</span></>}
          {ct && <span>· {ct.emoji} {ct.label}</span>}
          {task.due && <span style={{color:'var(--text-faint)'}}>· {ccRel(task.due)}</span>}
        </div>
        {task.description && <div className="cc-list-caption">{task.description.slice(0,80)}{task.description.length>80?'…':''}</div>}
      </div>
      <div onClick={e=>e.stopPropagation()}>
        <select className="cc-status-select" value={task.contentStatus||'brief'}
          style={{borderColor: cs?.color, color: cs?.color}}
          onChange={e => onStatusChange(e.target.value)}>
          {CONTENT_STATUSES.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
        </select>
      </div>
    </div>
  );
}

/* ── Pipeline (Kanban benzeri onay akışı) ─────────────────── */
function ContentPipeline({ tasks, projById, onSelectTask, onUpdateTask, onNew }) {
  const [drag, setDrag] = React.useState(null);

  const drop = (statusId) => {
    if (drag) onUpdateTask(drag, { contentStatus: statusId });
    setDrag(null);
  };

  return (
    <div className="cc-pipeline">
      <div className="cc-pipeline-topbar">
        <button className="btn btn-primary btn-sm" onClick={onNew}>
          <CCIcons.Plus size={13}/> Yeni İçerik
        </button>
      </div>
      <div className="cc-pipeline-board">
        {CONTENT_STATUSES.map(status => {
          const colTasks = tasks.filter(t => (t.contentStatus||'brief') === status.id);
          return (
            <div key={status.id} className="cc-pipeline-col"
              onDragOver={e => e.preventDefault()}
              onDrop={() => drop(status.id)}>
              <div className="cc-pipeline-col-hdr" style={{borderTopColor:status.color}}>
                <span className="cc-sdot" style={{background:status.color}}/>
                <span>{status.label}</span>
                <span className="sprint-col-count">{colTasks.length}</span>
              </div>
              <div className="cc-pipeline-col-body">
                {colTasks.length === 0 && (
                  <div className="cc-pipeline-empty">Boş</div>
                )}
                {colTasks.map(t => {
                  const pf = PLATFORMS.find(p => p.id === t.platform);
                  const ct = CONTENT_TYPES.find(c => c.id === t.contentType);
                  return (
                    <div key={t.id} className="cc-pipeline-card"
                      draggable onDragStart={() => setDrag(t.id)} onDragEnd={() => setDrag(null)}
                      onClick={() => onSelectTask(t.id)}>
                      <div className="cc-pipeline-card-top">
                        <span className="cc-pbadge" style={{background:pf?.color}}>{pf?.short}</span>
                        {ct && <span className="cc-type-emoji">{ct.emoji}</span>}
                        {t.due && <span className="cc-pipeline-date">{ccRel(t.due)}</span>}
                      </div>
                      <div className="cc-pipeline-card-title">{t.title}</div>
                      {projById[t.projectId] && (
                        <div className="cc-pipeline-client">
                          <span className="project-dot" style={{background:projById[t.projectId].color}}/>
                          {projById[t.projectId].name}
                        </div>
                      )}
                      {t.description && (
                        <div className="cc-pipeline-caption">{t.description.slice(0,60)}{t.description.length>60?'…':''}</div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ── İçerik oluştur modal ──────────────────────────────────── */
function ContentCreateModal({ date, state, onSave, onClose }) {
  const [platform,      setPF]  = React.useState('instagram');
  const [contentType,   setCT]  = React.useState('post');
  const [title,         setTT]  = React.useState('');
  const [caption,       setCA]  = React.useState('');
  const [projectId,     setPJ]  = React.useState(state.activeProjectId || state.projects[0]?.id || '');
  const [postDate,      setPD]  = React.useState(date || new Date().toISOString().slice(0,10));
  const [contentStatus, setCS]  = React.useState('brief');

  const selPf = PLATFORMS.find(p => p.id === platform);

  const save = () => {
    if (!title.trim()) return;
    onSave({
      title: title.trim(),
      description: caption.trim(),
      due: postDate || null,
      projectId,
      platform,
      contentType,
      contentStatus,
      status: 'todo',
      priority: 'medium',
    });
  };

  return (
    <div className="confirm-overlay" onClick={onClose}>
      <div className="cc-create-modal" onClick={e => e.stopPropagation()}>
        <div className="cc-create-modal-hdr" style={{borderBottomColor: selPf?.color}}>
          <span className="cc-pbadge" style={{background:selPf?.color,width:22,height:22,fontSize:10}}>{selPf?.short}</span>
          <h3>Yeni İçerik Planı</h3>
          <button className="icon-btn icon-btn-sm" onClick={onClose}><CCIcons.X size={16}/></button>
        </div>

        <div className="cc-create-body">
          {/* Platform */}
          <div className="cc-create-section">
            <div className="field-label">Platform</div>
            <div className="cc-platform-picker">
              {PLATFORMS.map(p => {
                const Icon = CCIcons[p.icon];
                return (
                  <button key={p.id}
                    className={`cc-pf-btn ${platform===p.id?'active':''}`}
                    style={platform===p.id ? {background:p.color,borderColor:p.color,color:'#fff'} : {}}
                    onClick={() => setPF(p.id)}>
                    {Icon && <Icon size={14}/>}
                    <span>{p.label}</span>
                  </button>
                );
              })}
            </div>
          </div>

          {/* İçerik tipi */}
          <div className="cc-create-section">
            <div className="field-label">İçerik Tipi</div>
            <div className="cc-type-picker">
              {CONTENT_TYPES.map(ct => (
                <button key={ct.id}
                  className={`cc-ct-btn ${contentType===ct.id?'active':''}`}
                  onClick={() => setCT(ct.id)}>
                  {ct.emoji} {ct.label}
                </button>
              ))}
            </div>
          </div>

          <label className="login-field">
            <span>Başlık (İç kullanım)</span>
            <input className="input" value={title} onChange={e => setTT(e.target.value)}
              placeholder="Mayıs kampanyası — ürün tanıtım postu" autoFocus
              onKeyDown={e => { if (e.key === 'Enter') save(); }} />
          </label>

          <label className="login-field">
            <span>Metin / Caption / Brief</span>
            <textarea className="input" rows={3} value={caption} onChange={e => setCA(e.target.value)}
              placeholder="Yayınlanacak post metni, brief veya yönlendirme..." />
          </label>

          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
            <label className="login-field">
              <span>Yayın Tarihi</span>
              <input type="date" className="input" value={postDate} onChange={e => setPD(e.target.value)} />
            </label>
            <label className="login-field">
              <span>Müşteri / Proje</span>
              <select className="input" value={projectId} onChange={e => setPJ(e.target.value)}>
                {state.projects.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
              </select>
            </label>
          </div>

          <label className="login-field">
            <span>Başlangıç Durumu</span>
            <div className="cc-status-picker">
              {CONTENT_STATUSES.map(s => (
                <button key={s.id}
                  className={`cc-status-btn ${contentStatus===s.id?'active':''}`}
                  style={contentStatus===s.id ? {background:`${s.color}20`,borderColor:s.color,color:s.color} : {}}
                  onClick={() => setCS(s.id)}>
                  {s.label}
                </button>
              ))}
            </div>
          </label>
        </div>

        <div className="cc-create-footer">
          <button className="btn btn-ghost btn-sm" onClick={onClose}>Vazgeç</button>
          <button className="btn btn-primary btn-sm" onClick={save} disabled={!title.trim()}>
            <CCIcons.Plus size={13}/> İçerik Oluştur
          </button>
        </div>
      </div>
    </div>
  );
}

/* ── Yardımcılar ───────────────────────────────────────────── */
function getWeekLabel(date) {
  const d = new Date(date); d.setHours(0,0,0,0);
  const day = (d.getDay() + 6) % 7;
  const mon = new Date(d); mon.setDate(d.getDate() - day);
  const sun = new Date(mon); sun.setDate(mon.getDate() + 6);
  const fmt = (dt) => `${dt.getDate()} ${MONTHS_TR[dt.getMonth()]}`;
  return `${fmt(mon)} – ${fmt(sun)}`;
}

window.ContentCalendar = ContentCalendar;
window.PLATFORMS       = PLATFORMS;
window.CONTENT_TYPES   = CONTENT_TYPES;
window.CONTENT_STATUSES = CONTENT_STATUSES;
