import { useState } from 'react';
import { Eye, EyeOff, Lock, Unlock, ChevronRight, ChevronDown } from 'lucide-react';

/**
 * DesignHierarchy — left panel tree of cover design elements.
 * Each item supports Select / Show / Hide / Isolate / Lock / Edit / View conflicts / View history.
 * Selecting an item fires onSelect with the element id so the viewport + inspector respond.
 */
const TREE = [
  { id: 'cover', label: 'Cover Design', icon: '◉', children: [
    { id: 'fit', label: 'Locked Fit Geometry', locked: true },
    { id: 'cover-shell', label: 'Conceptual Outer Cover' },
    { id: 'panels', label: 'Cover Panels' },
    { id: 'vent', label: 'Ventilation Concept' },
    { id: 'ossiguard', label: 'Ossiguard Interface' },
    { id: 'zones', label: 'Protected Zones', locked: true },
    { id: 'branding', label: 'SHiRE Branding' },
    { id: 'custom-text', label: 'Custom Text' },
    { id: 'patterns', label: 'Patterns' },
    { id: 'accents', label: 'Surface Accents' },
    { id: 'colour', label: 'Colour and Finish' },
  ]},
];

export default function DesignHierarchy({ selected, onSelect, visibility, onToggleVisibility, locks, onToggleLock, conflicts }) {
  const [expanded, setExpanded] = useState({ cover: true });
  const [isolated, setIsolated] = useState(null);

  const isolate = (id) => {
    setIsolated(isolated === id ? null : id);
    TREE[0].children.forEach((c) => onToggleVisibility(c.id, isolated === id ? true : c.id === id));
  };

  const renderNode = (node, depth = 0) => {
    const isSelected = selected === node.id;
    const isVisible = visibility[node.id] !== false;
    const isLocked = node.locked || locks[node.id];
    const hasConflict = conflicts && conflicts[node.id];
    return (
      <div key={node.id}>
        <div
          className={`group flex items-center gap-1 rounded-lg px-2 py-1.5 text-sm transition ${isSelected ? 'bg-shire-purple/15 text-violet-200' : 'text-slate-300 hover:bg-white/5'}`}
          style={{ paddingLeft: `${depth * 14 + 8}px` }}
        >
          {node.children ? (
            <button onClick={() => setExpanded((e) => ({ ...e, [node.id]: !e[node.id] }))} className="shrink-0 text-slate-500">
              {expanded[node.id] ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
            </button>
          ) : <span className="w-3.5 shrink-0" />}
          <button onClick={() => onSelect(node.id)} className="flex-1 text-left">
            <span className={hasConflict ? 'text-red-300' : ''}>{node.label}</span>
            {hasConflict && <span className="ml-1.5 inline-block h-1.5 w-1.5 rounded-full bg-red-400" />}
          </button>
          {node.children ? null : (
            <span className="flex shrink-0 items-center gap-0.5 opacity-0 transition group-hover:opacity-100">
              <button onClick={() => onToggleVisibility(node.id, !isVisible)} className="rounded p-0.5 hover:bg-white/10" title={isVisible ? 'Hide' : 'Show'}>
                {isVisible ? <Eye className="h-3.5 w-3.5" /> : <EyeOff className="h-3.5 w-3.5 text-slate-500" />}
              </button>
              {!node.locked && (
                <button onClick={() => onToggleLock(node.id, !isLocked)} className="rounded p-0.5 hover:bg-white/10" title={isLocked ? 'Unlock' : 'Lock'}>
                  {isLocked ? <Lock className="h-3.5 w-3.5 text-amber-400" /> : <Unlock className="h-3.5 w-3.5" />}
                </button>
              )}
            </span>
          )}
          {isLocked && <Lock className="h-3 w-3 shrink-0 text-amber-400/70" />}
        </div>
        {node.children && expanded[node.id] && node.children.map((c) => renderNode(c, depth + 1))}
      </div>
    );
  };

  return (
    <div className="panel flex h-full flex-col">
      <div className="border-b border-shire-border px-4 py-3">
        <h2 className="section-title mb-0">Design Hierarchy</h2>
        <p className="text-xs text-slate-500">Select an element to inspect it. Fit and protected zones are locked.</p>
      </div>
      <div className="flex-1 overflow-y-auto p-2">
        {TREE.map((n) => renderNode(n))}
      </div>
      {isolated && (
        <div className="border-t border-shire-border px-4 py-2 text-xs text-violet-300">
          Isolated: {TREE[0].children.find((c) => c.id === isolated)?.label} · <button onClick={() => isolate(isolated)} className="underline">clear</button>
        </div>
      )}
    </div>
  );
}