// special.jsx — Special Tasks panel (งานพิเศษ)
// 2 lanes: เคลม / ส่งไม่ครบ — พร้อมแนบรูปภาพ

const { useState, useEffect, useRef } = React;

const LANES = [
  {
    id: 'claim',
    label: 'ส่งของเคลม',
    icon: `<svg width="14" height="14" viewBox="0 0 16 16" fill="none">
      <path d="M8 2L2 14h12L8 2z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round" fill="none"/>
      <path d="M8 7v3M8 11.5v.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
    </svg>`,
    color: 'oklch(0.52 0.22 18)',
    tint: 'oklch(0.975 0.018 18)',
    border: 'oklch(0.84 0.08 18)',
  },
  {
    id: 'incomplete',
    label: 'ส่งของไม่ครบ',
    icon: `<svg width="14" height="14" viewBox="0 0 16 16" fill="none">
      <rect x="2" y="5" width="12" height="9" rx="1.5" stroke="currentColor" strokeWidth="1.3"/>
      <path d="M5 5V4a3 3 0 0 1 6 0v1" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
      <path d="M6 9h2M10 9h0" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
    </svg>`,
    color: 'oklch(0.48 0.16 240)',
    tint: 'oklch(0.975 0.018 240)',
    border: 'oklch(0.84 0.07 240)',
  },
];

function uid() { return 'sp-' + Math.random().toString(36).slice(2, 9); }

// ── Supabase helpers ───────────────────────────────────────────
async function fetchSpecialTasks() {
  const { data, error } = await window.db
    .from('special_tasks')
    .select('lane, data')
    .order('created_at', { ascending: true });
  if (error) { console.error('fetchSpecialTasks:', error); return { claim: [], incomplete: [] }; }
  const result = { claim: [], incomplete: [] };
  for (const row of (data || [])) {
    if (result[row.lane]) result[row.lane].push(row.data);
  }
  return result;
}
function syncTask(laneId, task) {
  window.db.from('special_tasks').upsert({ id: task.id, lane: laneId, data: task });
}
function removeTask(id) {
  window.db.from('special_tasks').delete().eq('id', id);
}

// ── Compress image to base64 (max 900px) ──────────────────────
async function compressImage(file, maxPx = 900) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const img = new Image();
      img.onload = () => {
        const scale = Math.min(1, maxPx / Math.max(img.width, img.height));
        const w = Math.round(img.width * scale);
        const h = Math.round(img.height * scale);
        const canvas = document.createElement('canvas');
        canvas.width = w; canvas.height = h;
        canvas.getContext('2d').drawImage(img, 0, 0, w, h);
        resolve(canvas.toDataURL('image/jpeg', 0.82));
      };
      img.onerror = reject;
      img.src = e.target.result;
    };
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

// ── Lightbox ──────────────────────────────────────────────────
function Lightbox({ src, onClose }) {
  useEffect(() => {
    const fn = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', fn);
    return () => window.removeEventListener('keydown', fn);
  }, [onClose]);
  return (
    <div className="lightbox-backdrop" onClick={onClose}>
      <img className="lightbox-img" src={src} onClick={e => e.stopPropagation()} alt="หลักฐาน" />
      <button className="lightbox-close" onClick={onClose}>×</button>
    </div>
  );
}

// ── ImageStrip — thumbnails per task ──────────────────────────
function ImageStrip({ images, taskId, onAdd, onRemove }) {
  const inp = useRef(null);
  const [lightbox, setLightbox] = useState(null);

  const handleFiles = async (files) => {
    for (const f of [...files]) {
      if (!f.type.startsWith('image/')) continue;
      try {
        const dataUrl = await compressImage(f);
        onAdd(taskId, { id: 'img-' + Math.random().toString(36).slice(2, 8), dataUrl });
      } catch (e) {}
    }
  };

  if (images.length === 0) {
    return (
      <div className="img-strip empty">
        <button className="img-add-btn" onClick={() => inp.current?.click()} title="แนบรูปภาพ">
          <svg width="12" height="12" viewBox="0 0 14 14" fill="none">
            <rect x="1" y="2" width="12" height="10" rx="1.5" stroke="currentColor" strokeWidth="1.2"/>
            <circle cx="4.5" cy="5.5" r="1" fill="currentColor"/>
            <path d="M1 9.5l3-3 2.5 2.5L9 7l4 3.5" stroke="currentColor" strokeWidth="1.1" strokeLinejoin="round"/>
            <path d="M10 0.5v3M8.5 2h3" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/>
          </svg>
          แนบรูป
        </button>
        <input ref={inp} type="file" accept="image/*" multiple style={{ display:'none' }}
          onChange={(e) => handleFiles(e.target.files)} />
      </div>
    );
  }

  return (
    <>
      <div className="img-strip">
        {images.map(img => (
          <div key={img.id} className="img-thumb-wrap">
            <img
              className="img-thumb"
              src={img.dataUrl}
              alt="หลักฐาน"
              onClick={() => setLightbox(img.dataUrl)}
              title="คลิกดูรูปเต็ม"
            />
            <button className="img-thumb-del" onClick={() => onRemove(taskId, img.id)} title="ลบรูป">×</button>
          </div>
        ))}
        <button className="img-add-more" onClick={() => inp.current?.click()} title="เพิ่มรูป">
          <svg width="11" height="11" viewBox="0 0 12 12">
            <path d="M6 1v10M1 6h10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
        </button>
        <input ref={inp} type="file" accept="image/*" multiple style={{ display:'none' }}
          onChange={(e) => handleFiles(e.target.files)} />
      </div>
      {lightbox && <Lightbox src={lightbox} onClose={() => setLightbox(null)} />}
    </>
  );
}

// ── AddTaskInline — inline input per lane ─────────────────────
function AddTaskInline({ onAdd, color }) {
  const [open, setOpen] = useState(false);
  const [text, setText] = useState('');
  const inp = useRef(null);

  const commit = () => {
    const v = text.trim();
    if (v) { onAdd(v); setText(''); setOpen(false); }
  };

  useEffect(() => { if (open) setTimeout(() => inp.current?.focus(), 50); }, [open]);

  if (!open) {
    return (
      <button className="sp-add-btn" onClick={() => setOpen(true)} style={{ '--lane-c': color }}>
        <svg width="11" height="11" viewBox="0 0 12 12">
          <path d="M6 1v10M1 6h10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
        </svg>
        เพิ่มงาน
      </button>
    );
  }

  return (
    <div className="sp-add-form">
      <input
        ref={inp}
        className="sp-add-input"
        placeholder="เลขออเดอร์ / รายละเอียด…"
        value={text}
        onChange={(e) => setText(e.target.value)}
        onKeyDown={(e) => { if (e.key === 'Enter') commit(); if (e.key === 'Escape') setOpen(false); }}
      />
      <button className="sp-add-ok" onClick={commit} style={{ background: color }}>บันทึก</button>
      <button className="sp-add-cancel" onClick={() => setOpen(false)}>×</button>
    </div>
  );
}

// ── TaskCard ──────────────────────────────────────────────────
function TaskCard({ task, color, onDone, onDelete, onAddImage, onRemoveImage }) {
  return (
    <div className={`sp-task ${task.done ? 'done' : ''}`}>
      <div className="sp-task-top">
        <button
          className="sp-check"
          style={task.done ? { background: color, borderColor: color } : { '--lane-c': color }}
          onClick={() => onDone(task.id)}
          title={task.done ? 'เลิกทำ' : 'ทำเสร็จแล้ว'}
        >
          {task.done && (
            <svg width="9" height="9" viewBox="0 0 10 10">
              <path d="M1.5 5 L4 7.5 L8.5 2.5" stroke="#fff" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          )}
        </button>
        <div className="sp-task-text">{task.text}</div>
        <div className="sp-task-time">{relTimeSpecial(task.created)}</div>
        <button className="sp-delete" onClick={() => onDelete(task.id)} title="ลบ">×</button>
      </div>
      <ImageStrip
        images={task.images || []}
        taskId={task.id}
        onAdd={onAddImage}
        onRemove={onRemoveImage}
      />
    </div>
  );
}

function relTimeSpecial(ts) {
  const m = Math.round((Date.now() - ts) / 60000);
  if (m < 1) return 'เมื่อกี้';
  if (m < 60) return `${m} นาที`;
  const h = Math.round(m / 60);
  if (h < 24) return `${h} ชม.`;
  return `${Math.round(h/24)} วัน`;
}

// ── Lane ─────────────────────────────────────────────────────
function Lane({ lane, tasks, onAdd, onDone, onDelete, onAddImage, onRemoveImage }) {
  const active = tasks.filter(t => !t.done);
  const done   = tasks.filter(t => t.done);

  return (
    <div className="sp-lane" style={{ '--lane-c': lane.color, '--lane-t': lane.tint, '--lane-b': lane.border }}>
      <div className="sp-lane-header">
        <span className="sp-lane-icon" dangerouslySetInnerHTML={{ __html: lane.icon }} />
        <span className="sp-lane-label">{lane.label}</span>
        {active.length > 0 && <span className="sp-lane-badge">{active.length}</span>}
      </div>
      <div className="sp-lane-body">
        {active.map(t => (
          <TaskCard key={t.id} task={t} color={lane.color}
            onDone={onDone} onDelete={onDelete}
            onAddImage={onAddImage} onRemoveImage={onRemoveImage} />
        ))}
        {done.map(t => (
          <TaskCard key={t.id} task={t} color={lane.color}
            onDone={onDone} onDelete={onDelete}
            onAddImage={onAddImage} onRemoveImage={onRemoveImage} />
        ))}
        {tasks.length === 0 && <div className="sp-empty">ไม่มีงานค้าง</div>}
        <AddTaskInline onAdd={(text) => onAdd(lane.id, text)} color={lane.color} />
      </div>
    </div>
  );
}

// ── SpecialPanel ──────────────────────────────────────────────
function SpecialPanel() {
  const [data, setData] = useState({ claim: [], incomplete: [] });
  const [collapsed, setCollapsed] = useState(false);

  useEffect(() => {
    fetchSpecialTasks().then(d => setData(d));
  }, []);

  const totalActive = LANES.reduce((s, l) => s + (data[l.id] || []).filter(t => !t.done).length, 0);

  const addTask = (laneId, text) => {
    const task = { id: uid(), text, done: false, created: Date.now(), images: [] };
    setData(prev => ({ ...prev, [laneId]: [...(prev[laneId]||[]), task] }));
    syncTask(laneId, task);
  };
  const toggleDone = (laneId, id) => setData(prev => {
    const next = { ...prev, [laneId]: prev[laneId].map(t => t.id===id ? {...t, done:!t.done} : t) };
    const task = next[laneId].find(t => t.id === id);
    if (task) syncTask(laneId, task);
    return next;
  });
  const deleteTask = (laneId, id) => {
    setData(prev => ({ ...prev, [laneId]: prev[laneId].filter(t => t.id!==id) }));
    removeTask(id);
  };
  const addImage = (laneId, taskId, img) => setData(prev => {
    const next = { ...prev, [laneId]: prev[laneId].map(t => t.id===taskId ? {...t, images:[...(t.images||[]),img]} : t) };
    const task = next[laneId].find(t => t.id === taskId);
    if (task) syncTask(laneId, task);
    return next;
  });
  const removeImage = (laneId, taskId, imgId) => setData(prev => {
    const next = { ...prev, [laneId]: prev[laneId].map(t => t.id===taskId ? {...t, images:(t.images||[]).filter(i=>i.id!==imgId)} : t) };
    const task = next[laneId].find(t => t.id === taskId);
    if (task) syncTask(laneId, task);
    return next;
  });

  return (
    <section className={`special-panel ${collapsed ? 'collapsed' : ''}`}>
      <div className="sp-header" onClick={() => setCollapsed(c => !c)}>
        <div className="sp-header-left">
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
            <path d="M3 4h10M3 8h7M3 12h5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
          </svg>
          <span className="sp-title">งานพิเศษ</span>
          {totalActive > 0
            ? <span className="sp-total-badge">{totalActive} รายการค้าง</span>
            : <span className="sp-all-clear">✓ เรียบร้อยทั้งหมด</span>
          }
        </div>
        <div className="sp-header-right">
          <div className="sp-lane-summary">
            {LANES.map(l => {
              const cnt = (data[l.id]||[]).filter(t=>!t.done).length;
              return cnt > 0 ? (
                <span key={l.id} className="sp-summary-chip" style={{ color: l.color, borderColor: l.border, background: l.tint }}>
                  {l.label} {cnt}
                </span>
              ) : null;
            })}
          </div>
          <svg width="10" height="10" viewBox="0 0 10 10"
            style={{ transform: collapsed ? 'rotate(0deg)' : 'rotate(90deg)', transition: 'transform .2s', color: 'var(--ink-3)' }}>
            <path d="M3 2 L7 5 L3 8" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
      </div>

      {!collapsed && (
        <div className="sp-body">
          {LANES.map(lane => (
            <Lane key={lane.id} lane={lane} tasks={data[lane.id]||[]}
              onAdd={addTask}
              onDone={(id) => toggleDone(lane.id, id)}
              onDelete={(id) => deleteTask(lane.id, id)}
              onAddImage={(taskId, img) => addImage(lane.id, taskId, img)}
              onRemoveImage={(taskId, imgId) => removeImage(lane.id, taskId, imgId)}
            />
          ))}
        </div>
      )}
    </section>
  );
}

Object.assign(window, { SpecialPanel });
