/* =========================================================================
   Çevik Yaşam — DASHBOARD (proje widget'ları + günün özeti)
   Her widget bir proje; içinde başlıklı bölümler ve çoklu linkler.
   Linkler yeni sekmede açılır. Widget'lar sürüklenip yeri değişir.
   ========================================================================= */

const DASH_DEFAULT = [
  { id: "w-antdis", title: "Antalya Diş", color: "#FF2939", sections: [
    { id: "s1", label: "Uzaktan reklamlar", links: [{ id: "l1", label: "Meta Ads", url: "https://business.facebook.com" }, { id: "l2", label: "Google Ads", url: "https://ads.google.com" }, { id: "l3", label: "Bitrix Report", url: "https://bitrix24.com" }] },
    { id: "s2", label: "Etkinlik reklamları", links: [{ id: "l4", label: "Meta Ads", url: "https://business.facebook.com" }, { id: "l5", label: "TikTok Ads", url: "https://ads.tiktok.com" }, { id: "l6", label: "UK Events", url: "" }, { id: "l7", label: "UK Budget", url: "" }] },
    { id: "s3", label: "Sosyal medya", links: [{ id: "l8", label: "Instagram (İng)", url: "https://instagram.com" }, { id: "l9", label: "Instagram (Rusça)", url: "https://instagram.com" }] },
  ] },
  { id: "w-imes", title: "İmes Spor", color: "#FF2939", sections: [
    { id: "s1", label: "Proforce Kurumsal", links: [{ id: "l1", label: "Instagram", url: "https://instagram.com" }, { id: "l2", label: "Meta Ads · 5k", url: "https://business.facebook.com" }, { id: "l3", label: "Google Ads · 60k", url: "https://ads.google.com" }] },
    { id: "s2", label: "Panatta Kurumsal", links: [{ id: "l4", label: "Instagram", url: "https://instagram.com" }, { id: "l5", label: "Meta Ads · 5k", url: "https://business.facebook.com" }, { id: "l6", label: "Google Ads · 30k", url: "https://ads.google.com" }] },
    { id: "s3", label: "Proforce Shop", links: [{ id: "l7", label: "Instagram", url: "https://instagram.com" }, { id: "l8", label: "Meta Catalog · 45k", url: "https://business.facebook.com" }, { id: "l9", label: "Google Ads · 45k", url: "https://ads.google.com" }] },
  ] },
  { id: "w-multi", title: "Multiligo", color: "#2B6CB0", sections: [
    { id: "s1", label: "Koop Akademi", links: [{ id: "l1", label: "KoopAkademi Pazarlama", url: "" }, { id: "l2", label: "Marketing Danışman TOR", url: "" }] },
    { id: "s2", label: "Kenan · Kale Vakfı", links: [{ id: "l3", label: "Meta Ads", url: "https://business.facebook.com" }, { id: "l4", label: "Google Adgrant", url: "https://ads.google.com" }, { id: "l5", label: "LinkedIn Ads", url: "https://linkedin.com" }, { id: "l6", label: "Looker Studio", url: "https://lookerstudio.google.com" }] },
  ] },
];

function LinkEditorSheet({ widget, onClose, onSave }) {
  const [w, setW] = useState(JSON.parse(JSON.stringify(widget)));
  const setTitle = (v) => setW((s) => ({ ...s, title: v }));
  const addSection = () => setW((s) => ({ ...s, sections: [...s.sections, { id: uid("s"), label: "", links: [] }] }));
  const setSec = (si, patch) => setW((s) => ({ ...s, sections: s.sections.map((x, i) => i === si ? { ...x, ...patch } : x) }));
  const delSec = (si) => setW((s) => ({ ...s, sections: s.sections.filter((_, i) => i !== si) }));
  const addLink = (si) => setSec(si, { links: [...w.sections[si].links, { id: uid("l"), label: "", url: "" }] });
  const setLink = (si, li, patch) => setSec(si, { links: w.sections[si].links.map((x, i) => i === li ? { ...x, ...patch } : x) });
  const delLink = (si, li) => setSec(si, { links: w.sections[si].links.filter((_, i) => i !== li) });

  return (
    <Sheet eyebrow={widget._new ? "Yeni widget" : "Widget'ı düzenle"} title="Proje widget'ı" onClose={onClose} maxWidth={620}
      footer={<React.Fragment>
        <Btn variant="ghost" onClick={onClose}>İptal</Btn>
        <Btn variant="primary" icon="check" onClick={() => onSave({ ...w, title: w.title.trim() || "Yeni widget" })}>Kaydet</Btn>
      </React.Fragment>}>
      <div className="cy-field">
        <label className="cy-label">Widget başlığı (proje)</label>
        <input className="cy-input" placeholder="örn. Antalya Diş" value={w.title} onChange={(e) => setTitle(e.target.value)} autoFocus />
      </div>
      {w.sections.map((sec, si) => (
        <div key={sec.id} className="cy-we-section">
          <div style={{ display: "flex", gap: 8, marginBottom: 8 }}>
            <input className="cy-input" style={{ fontWeight: 600, fontSize: 13.5 }} placeholder="Bölüm başlığı (örn. Uzaktan reklamlar)" value={sec.label} onChange={(e) => setSec(si, { label: e.target.value })} />
            <button className="cy-iconbtn-sm" onClick={() => delSec(si)} title="Bölümü sil"><Icon name="trash" style={{ width: 15 }} /></button>
          </div>
          {sec.links.map((l, li) => (
            <div key={l.id} style={{ display: "flex", gap: 6, marginBottom: 6 }}>
              <input className="cy-input" style={{ flex: "1 1 120px", padding: "7px 10px", fontSize: 13 }} placeholder="Link adı" value={l.label} onChange={(e) => setLink(si, li, { label: e.target.value })} />
              <input className="cy-input" style={{ flex: "2 1 160px", padding: "7px 10px", fontSize: 13 }} placeholder="https://…" value={l.url} onChange={(e) => setLink(si, li, { url: e.target.value })} />
              <button className="cy-iconbtn-sm" onClick={() => delLink(si, li)}><Icon name="x" style={{ width: 13 }} /></button>
            </div>
          ))}
          <button className="cy-btn ghost sm" style={{ marginTop: 2, color: "var(--ml-ink-4)" }} onClick={() => addLink(si)}><Icon name="plus" className="ic" /> Link ekle</button>
        </div>
      ))}
      <button className="cy-addbtn-dashed" style={{ marginTop: 12 }} onClick={addSection}><Icon name="plus" className="ic" /> Bölüm ekle</button>
    </Sheet>
  );
}

function DashWidget({ w, onEdit, onDelete, dragHandlers }) {
  return (
    <div className="cy-widget" {...dragHandlers}>
      <div className="cy-widget-head" style={{ borderColor: w.color }}>
        <span className="cy-widget-grip" title="Sürükle"><Icon name="more" style={{ width: 15 }} /></span>
        <i className="cy-proj-dot" style={{ background: w.color, width: 9, height: 9 }} />
        <h4 className="cy-widget-title">{w.title}</h4>
        <RowMenu onEdit={() => onEdit(w)} onDelete={() => onDelete(w)} />
      </div>
      <div className="cy-widget-body">
        {w.sections.map((sec) => (
          <div key={sec.id} className="cy-widget-sec">
            {sec.label && <div className="cy-widget-sec-label">{sec.label}</div>}
            <div className="cy-widget-links">
              {sec.links.map((l) => (
                l.url
                  ? <a key={l.id} href={l.url} target="_blank" rel="noreferrer" className="cy-widget-link"><Icon name="arrowUpRight" style={{ width: 13 }} />{l.label}</a>
                  : <span key={l.id} className="cy-widget-link disabled">{l.label}</span>
              ))}
              {!sec.links.length && <span className="cy-muted" style={{ fontSize: 12 }}>—</span>}
            </div>
          </div>
        ))}
        {!w.sections.length && <div className="cy-muted" style={{ fontSize: 12.5, padding: "8px 0" }}>Bölüm yok. Düzenle ile link ekle.</div>}
      </div>
    </div>
  );
}

function Dashboard() {
  const W = useCollection("dashboard-widgets", DASH_DEFAULT);
  const T = useCollection("tasks", CY.todayTasks);
  const [stress] = useStore("stress", CY.stressNow);
  const [edit, setEdit] = useState(null);
  const [del, setDel] = useState(null);
  const dragId = useRef(null);
  const [over, setOver] = useState(null);

  const widgets = W.active;
  const todayList = T.active.filter((t) => t.today);
  const done = todayList.filter((t) => t.done).length;
  const overdue = T.active.filter((t) => !t.done && t.due && t.due < CY.today.iso).length;
  const nextDate = (CY.criticalDates || []).map((d) => ({ ...d, d: CY.daysUntil(d.date) })).filter((d) => d.d >= 0).sort((a, b) => a.d - b.d)[0];

  const onDrop = (targetId) => {
    if (!dragId.current || dragId.current === targetId) { setOver(null); return; }
    const arr = [...W.items];
    const from = arr.findIndex((x) => x.id === dragId.current);
    const to = arr.findIndex((x) => x.id === targetId);
    const [m] = arr.splice(from, 1); arr.splice(to, 0, m);
    W.setItems(arr); dragId.current = null; setOver(null);
  };

  const W_STATS = [
    { lab: "Bugün", val: `${done}/${todayList.length}`, sub: "tamamlandı", color: "var(--ml-ink)", go: "bugun" },
    { lab: "Genel rahatlık", val: stress, sub: stressLabel(stress), color: stressColor(stress), go: "bugun" },
    { lab: "Sıradaki tarih", val: nextDate ? (nextDate.d === 0 ? "Bugün" : nextDate.d + "g") : "—", sub: nextDate ? nextDate.title : "yok", color: nextDate && nextDate.d <= 3 ? "var(--ml-red)" : "var(--ml-ink)", go: "tarihler" },
    { lab: "Gecikmiş", val: overdue, sub: "iş", color: overdue ? "var(--ml-red)" : "var(--ml-ink)", go: "gorevler" },
  ];

  return (
    <div className="cy-canvas cy-fade-in" style={{ maxWidth: 1240 }}>
      <SectionHead eyebrow={CY.today.label + " · " + CY.today.week}
        title={CY.buildGreeting({ name: CY.user.name, stress: stress, todayCount: todayList.length, doneCount: done, overdue: overdue, deferred: 0, hour: new Date().getHours() })}
        sub="Günün özeti ve proje kısayolları. Her widget bir proje; içine bölüm ve çoklu link eklersin. Linkler yeni sekmede açılır; widget'ları sürükleyip dizebilirsin."
        right={<Btn variant="primary" icon="plus" onClick={() => setEdit({ _new: true, id: uid("w"), title: "", color: "#FF2939", sections: [{ id: uid("s"), label: "", links: [] }] })}>Widget ekle</Btn>} />

      <CriticalAlert tasks={T.active} onGoto={(id) => { T.update(id, { today: true, parked: false }); try { localStorage.setItem("cy:active-task", JSON.stringify(id)); if (window.CY_STATE) window.CY_STATE["cy:active-task"] = id; window.cySaveState && window.cySaveState("cy:active-task", id); } catch (e) {} window.cyGoto("bugun"); }} onEngel={() => window.cyGoto("engeller")} />

      <div className="cy-dash-widgets">
        {W_STATS.map((s, i) => (
          <Card key={i} className="flat" style={{ cursor: "pointer" }} onClick={() => window.cyGoto(s.go)}>
            <Eyebrow>{s.lab}</Eyebrow>
            <div style={{ fontSize: 28, fontWeight: 700, marginTop: 8, color: s.color, letterSpacing: "-0.02em" }}>{s.val}</div>
            <div className="cy-muted" style={{ fontSize: 12, marginTop: 4, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{s.sub}</div>
          </Card>
        ))}
      </div>

      <h3 className="cy-h3" style={{ margin: "28px 0 14px" }}>Proje widget'ları</h3>
      <div className="cy-widget-grid">
        {widgets.map((w) => (
          <div key={w.id}
            className={over === w.id ? "cy-widget-wrap over" : "cy-widget-wrap"}
            onDragOver={(e) => { e.preventDefault(); setOver(w.id); }}
            onDragLeave={() => setOver(null)}
            onDrop={() => onDrop(w.id)}>
            <DashWidget w={w} onEdit={setEdit} onDelete={setDel}
              dragHandlers={{ draggable: true, onDragStart: () => { dragId.current = w.id; } }} />
          </div>
        ))}
        <button className="cy-widget-add" onClick={() => setEdit({ _new: true, id: uid("w"), title: "", color: "#FF2939", sections: [{ id: uid("s"), label: "", links: [] }] })}>
          <Icon name="plus" style={{ width: 22 }} /><span>Widget ekle</span>
        </button>
      </div>

      {edit && <LinkEditorSheet widget={edit} onClose={() => setEdit(null)}
        onSave={(w) => { const { _new, ...clean } = w; edit._new ? W.add(clean) : W.update(edit.id, clean); setEdit(null); }} />}
      {del && <ConfirmSheet body={`"${del.title}" widget'ı silinecek.`} onClose={() => setDel(null)} onConfirm={() => { W.remove(del.id); setDel(null); }} />}
    </div>
  );
}

Object.assign(window, { Dashboard });
