// UI chrome: file-tree sidebar, top bar, annotation toolbar.
const { useState } = React;
const I = window.Icons;

// ---------- File tree ----------
function FileRow({ node, depth, activeId, openNote, progressOf, annoCountOf }) {
  const prog = progressOf(node.id);
  const ac = annoCountOf(node.id);
  return (
    <button className={"tree-file" + (activeId === node.id ? " active" : "")}
      style={{ paddingLeft: depth * 16 + 10 }} onClick={() => openNote(node.id)}>
      <span className="md-ic">M<span className="md-arr">↓</span></span>
      <span className="tree-label">{node.name}</span>
      {ac > 0 && <span className="tree-anno" title={ac + " işaret"}>{ac}</span>}
      <span className={"tree-dot" + (prog >= 100 ? " done" : prog > 0 ? " started" : "")} title={Math.round(prog) + "%"} />
    </button>
  );
}

function FolderRow({ node, depth, expanded, toggle, ...rest }) {
  const open = expanded.has(node.id);
  return (
    <div className="tree-folder-wrap">
      <button className="tree-folder" style={{ paddingLeft: depth * 16 + 6 }} onClick={() => toggle(node.id)}>
        <span className={"tree-caret" + (open ? " open" : "")}><I.chevron size={14} /></span>
        <span className="tree-fic"><I.folder size={15} /></span>
        <span className="tree-label">{node.name}</span>
      </button>
      {open && node.children.map((ch) => (
        <TreeNode key={ch.id} node={ch} depth={depth + 1} expanded={expanded} toggle={toggle} {...rest} />
      ))}
    </div>
  );
}

function TreeNode(props) {
  return props.node.type === "folder" ? <FolderRow {...props} /> : <FileRow {...props} />;
}

function Sidebar({ tree, rootName, activeId, openNote, search, setSearch, allTags, activeTags,
  toggleTag, clearTags, expanded, toggle, progressOf, annoCountOf, fileCount }) {
  const [tagLimit, setTagLimit] = useState(10);
  return (
    <aside className="sidebar">
      <div className="sb-brand">
        <div className="sb-logo">
          <img className="sb-logo-img logo-dark" src="icons/White.png" alt="" />
          <img className="sb-logo-img logo-light" src="icons/Black.png" alt="" />
        </div>
        <div>
          <div className="sb-title">Study Canvas</div>
          <div className="sb-sub">{fileCount} not · {rootName}</div>
        </div>
      </div>

      <div className="sb-search">
        <span className="sb-search-ic"><I.search size={16} /></span>
        <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Notlarda ara…" />
        {search && <button className="sb-search-clear" onClick={() => setSearch("")}><I.close size={14} /></button>}
      </div>

      {allTags.length > 0 && (
        <div className="sb-tag-row">
          {allTags.slice(0, tagLimit).map((t) => (
            <button key={t} className={"chip" + (activeTags.includes(t) ? " on" : "")}
              onClick={() => toggleTag(t)}>{t}</button>
          ))}
          {allTags.length > tagLimit && (
            <button className="chip more" onClick={() => setTagLimit((l) => l + 10)}>
              +{Math.min(10, allTags.length - tagLimit)} daha
            </button>
          )}
          {tagLimit > 10 && (
            <button className="chip more" onClick={() => setTagLimit(10)}>Daha az</button>
          )}
          {activeTags.length > 0 && (
            <button className="chip clear" onClick={clearTags} title="Etiket filtresini temizle">
              <I.close size={12} /> Temizle
            </button>
          )}
        </div>
      )}

      <div className="tree">
        <div className="tree-root">
          <span className="tree-fic open"><I.book size={15} /></span>
          <span className="tree-label">{rootName}</span>
        </div>
        {tree.length === 0 && <div className="sb-empty">Eşleşen not yok.</div>}
        {tree.map((n) => (
          <TreeNode key={n.id} node={n} depth={1} expanded={expanded} toggle={toggle}
            activeId={activeId} openNote={openNote} progressOf={progressOf} annoCountOf={annoCountOf} />
        ))}
      </div>
    </aside>
  );
}

// ---------- Top bar ----------
function TopBar({ note, crumbs, onCrumb, progress, theme, toggleTheme, focus, toggleFocus,
  leftOpen, toggleLeft, rightOpen, toggleRight }) {
  return (
    <header className="topbar">
      <div className="tb-left">
        <button className="icon-btn" title="Kütüphane" onClick={toggleLeft}>
          <I.panelLeft size={19} />
        </button>
        <div className="tb-crumb">
          {crumbs.map((c, i) => (
            <span key={c.id} className="tb-seg">
              <button className="tb-folder tb-crumb-btn" onClick={() => onCrumb(i)}>{c.name}</button>
              <I.chevron size={13} />
            </span>
          ))}
          <span className="tb-note">{note ? note.name : "—"}</span>
        </div>
      </div>
      <div className="tb-right">
        <div className="tb-progress" title="Okuma ilerlemesi">
          <svg width="34" height="34" viewBox="0 0 34 34" className="ring">
            <circle cx="17" cy="17" r="14" className="ring-bg" />
            <circle cx="17" cy="17" r="14" className="ring-fg"
              strokeDasharray={2 * Math.PI * 14}
              strokeDashoffset={2 * Math.PI * 14 * (1 - progress / 100)} />
          </svg>
          <span className="ring-label">{Math.round(progress)}</span>
        </div>
        <button className="icon-btn" title="Odak modu" onClick={toggleFocus}>
          <I.focus size={19} style={{ opacity: focus ? 1 : 0.7 }} />
        </button>
        <button className="icon-btn" title="Tema" onClick={toggleTheme}>
          {theme === "dark" ? <I.sun size={19} /> : <I.moon size={19} />}
        </button>
        <button className={"icon-btn" + (rightOpen ? " on" : "")} title="Yan panel" onClick={toggleRight}>
          <I.panelRight size={19} />
        </button>
      </div>
    </header>
  );
}

// ---------- Annotation toolbar ----------
const TOOLS = [
  { id: "read", icon: "cursor", label: "Oku / Gez" },
  { id: "highlight", icon: "highlighter", label: "Vurgula" },
  { id: "note", icon: "note", label: "Yapışkan not" },
  { id: "comment", icon: "comment", label: "Kenar yorumu" },
  { id: "pen", icon: "pen", label: "Kalem" },
  { id: "eraser", icon: "eraser", label: "Silgi" },
];

// Custom color: pick into a draft, then commit with an explicit "Ekle" button —
// avoids the native color input firing on every drag and flooding the palette.
function CustomColorAdd({ round, sm, onAdd }) {
  const [open, setOpen] = useState(false);
  const [draft, setDraft] = useState("#5ec9b7");
  return (
    <span className="cc-wrap">
      <button className={"swatch add" + (round ? " round" : "") + (sm ? " sm" : "")}
        title="Özel renk ekle" onClick={() => setOpen((o) => !o)}><I.plus size={sm ? 12 : 14} /></button>
      {open && (
        <div className="cc-pop" onMouseDown={(e) => e.stopPropagation()}>
          <input type="color" value={draft} onChange={(e) => setDraft(e.target.value)} />
          <span className="cc-preview" style={{ background: draft }} />
          <button className="cc-add" onClick={() => { onAdd(draft); setOpen(false); }}>Ekle</button>
        </div>
      )}
    </span>
  );
}

function Toolbar({ tool, setTool, hlColors, hlColor, setHlColor, penColors, penColor, setPenColor,
  onAddHlColor, onAddPenColor, penWidth, setPenWidth, onUndoStroke, onClear, hint }) {
  const showHlColors = tool === "highlight" || tool === "note";
  const showPen = tool === "pen";
  return (
    <div className="toolbar-wrap">
      {hint && <div className="tool-hint">{hint}</div>}
      <div className="toolbar">
        {showHlColors && (
          <div className="tb-swatches">
            {hlColors.map((c) => (
              <button key={c.id} className={"swatch" + (hlColor === c.id ? " on" : "")}
                style={{ "--sw": c.solid }} title={c.label} onClick={() => setHlColor(c.id)} />
            ))}
            <CustomColorAdd onAdd={onAddHlColor} />
            <div className="tb-divider" />
          </div>
        )}
        {showPen && (
          <div className="tb-swatches">
            {penColors.map((c) => (
              <button key={c.id} className={"swatch round" + (penColor === c.id ? " on" : "")}
                style={{ "--sw": c.solid }} title={c.label} onClick={() => setPenColor(c.id)} />
            ))}
            <CustomColorAdd round onAdd={onAddPenColor} />
            <div className="tb-divider" />
            {[2, 4, 7].map((w) => (
              <button key={w} className={"pen-w" + (penWidth === w ? " on" : "")}
                onClick={() => setPenWidth(w)}><span style={{ width: w + 2, height: w + 2 }} /></button>
            ))}
            <button className="icon-btn sm" title="Son çizgiyi geri al" onClick={onUndoStroke}><I.undo size={16} /></button>
            <div className="tb-divider" />
          </div>
        )}
        <div className="tb-tools">
          {TOOLS.map((t) => {
            const C = I[t.icon];
            return (
              <button key={t.id} className={"tool" + (tool === t.id ? " on" : "")}
                title={t.label} onClick={() => setTool(t.id)}>
                <C size={20} />
              </button>
            );
          })}
        </div>
        <div className="tb-divider" />
        <button className="icon-btn sm" title="Bu sayfadaki işaretleri temizle" onClick={onClear}><I.trash size={17} /></button>
      </div>
    </div>
  );
}

Object.assign(window, { Sidebar, TopBar, Toolbar, TOOLS });
