// screen-editor.jsx — App editor: section list + live reactive phone preview + properties panel
// Exports: EditorScreen

const DEFAULT_SECTIONS = [
  { id: 'hero',        label: 'Hero banner',       icon: 'image',            enabled: true,  locked: false },
  { id: 'featured',    label: 'Featured products', icon: 'grid',             enabled: true,  locked: false },
  { id: 'collections', label: 'Collections grid',  icon: 'layout-grid',      enabled: true,  locked: false },
  { id: 'banner2',     label: 'Promo banner',       icon: 'megaphone',        enabled: false, locked: false },
  { id: 'reviews',     label: 'Reviews (Judge.me)', icon: 'star',             enabled: true,  locked: false },
  { id: 'tabbar',      label: 'Tab bar',            icon: 'layout-dashboard', enabled: true,  locked: true  },
];

const HERO_STYLES    = ['Editorial dark', 'Clean light', 'Honey accent', 'Full-bleed'];
const LAYOUT_STYLES  = ['2-column grid', 'Horizontal scroll', 'Full-width list'];
const REVIEW_PLACEMENTS = [
  { id: 'below_description', label: 'Below product description' },
  { id: 'above_atc',         label: 'Above add-to-cart' },
  { id: 'bottom',            label: 'Bottom of page' },
];

// Per-section default editable properties
const DEFAULT_SECTION_PROPS = {
  hero:        { style: 0, headline: '', cta: 'Shop now →' },
  featured:    { layout: 0, perRow: '2', maxItems: '8' },
  collections: { style: 'Grid', title: 'Shop by category' },
  banner2:     { headline: '', code: 'SAVE20', btnText: 'Claim offer →' },
  reviews:     { count: '3', placement: 'below_description', showRating: true },
};

// ---- Section row in left panel ----
const SectionRow = ({ section, index, total, onMove, onToggle, onSelect, selected }) => {
  const [hovered, setHovered] = React.useState(false);
  const isActive = selected === section.id;
  return (
    <div
      onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)}
      onClick={() => !section.locked && onSelect(isActive ? null : section.id)}
      style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '9px 10px', borderRadius: 8, cursor: section.locked ? 'default' : 'pointer', background: isActive ? 'var(--ink)' : hovered ? 'var(--ink-04)' : 'transparent', color: isActive ? 'var(--paper)' : 'var(--fg-1)', border: `1px solid ${isActive ? 'var(--ink)' : 'transparent'}`, transition: 'all 140ms var(--ease)', userSelect: 'none' }}>
      {/* Grip */}
      <div style={{ cursor: section.locked ? 'default' : 'grab', opacity: section.locked ? 0.15 : 0.35, flexShrink: 0, color: 'currentColor' }}>
        <i data-lucide="grip-vertical" style={{ width: 13, height: 13 }}></i>
      </div>
      {/* Icon */}
      <div style={{ width: 26, height: 26, borderRadius: 6, background: isActive ? 'rgba(255,255,255,0.12)' : 'var(--sand-50)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <i data-lucide={section.icon} style={{ width: 12, height: 12 }}></i>
      </div>
      {/* Label */}
      <span style={{ flex: 1, fontSize: 12, fontWeight: isActive ? 500 : 400, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{section.label}</span>
      {/* Lock */}
      {section.locked && <i data-lucide="lock" style={{ width: 10, height: 10, opacity: 0.3, flexShrink: 0 }}></i>}
      {/* Move buttons */}
      {!section.locked && (hovered || isActive) && (
        <div style={{ display: 'flex', gap: 1, flexShrink: 0 }} onClick={e => e.stopPropagation()}>
          <button onClick={() => onMove(index, -1)} disabled={index === 0} style={{ width: 20, height: 20, borderRadius: 4, border: 'none', background: 'transparent', cursor: index === 0 ? 'not-allowed' : 'pointer', color: 'currentColor', opacity: index === 0 ? 0.2 : 0.7, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <i data-lucide="chevron-up" style={{ width: 11, height: 11 }}></i>
          </button>
          <button onClick={() => onMove(index, 1)} disabled={index >= total - 1} style={{ width: 20, height: 20, borderRadius: 4, border: 'none', background: 'transparent', cursor: index >= total - 1 ? 'not-allowed' : 'pointer', color: 'currentColor', opacity: index >= total - 1 ? 0.2 : 0.7, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <i data-lucide="chevron-down" style={{ width: 11, height: 11 }}></i>
          </button>
        </div>
      )}
      {/* Toggle */}
      {!section.locked && (
        <div onClick={e => { e.stopPropagation(); onToggle(section.id); }}>
          <div style={{ width: 30, height: 17, borderRadius: 999, background: section.enabled ? (isActive ? 'var(--honey)' : 'var(--ink)') : (isActive ? 'rgba(255,255,255,0.25)' : 'var(--sand-200)'), position: 'relative', cursor: 'pointer', transition: 'background 200ms', flexShrink: 0 }}>
            <div style={{ position: 'absolute', top: 2.5, left: section.enabled ? 15 : 2.5, width: 12, height: 12, borderRadius: '50%', background: isActive ? 'var(--ink)' : 'var(--white)', transition: 'left 200ms var(--ease)' }}></div>
          </div>
        </div>
      )}
    </div>
  );
};

// ---- Properties panel ----
const PropertiesPanel = ({ section, sectionProps, onPropChange, persona }) => {
  if (!section) return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: 12, color: 'var(--fg-3)', textAlign: 'center', padding: 24 }}>
      <i data-lucide="mouse-pointer-2" style={{ width: 26, height: 26 }}></i>
      <div style={{ fontSize: 12, lineHeight: 1.6 }}>Select a section<br/>to configure it</div>
    </div>
  );

  const props = sectionProps[section.id] || {};
  const set = (key, val) => onPropChange(section.id, key, val);

  const RadioGroup = ({ label, options, value, onChange }) => (
    <div>
      <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--fg-2)', marginBottom: 7 }}>{label}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        {options.map((opt, i) => {
          const id = typeof opt === 'object' ? opt.id : i;
          const lbl = typeof opt === 'object' ? opt.label : opt;
          return (
            <div key={id} onClick={() => onChange(id)} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 9px', borderRadius: 7, cursor: 'pointer', background: value === id ? 'var(--ink-08)' : 'transparent', border: `1px solid ${value === id ? 'var(--hairline-bold)' : 'transparent'}` }}>
              <div style={{ width: 12, height: 12, borderRadius: '50%', border: `2px solid ${value === id ? 'var(--ink)' : 'var(--sand-300)'}`, background: value === id ? 'var(--ink)' : 'transparent', flexShrink: 0 }}></div>
              <span style={{ fontSize: 12, fontWeight: value === id ? 500 : 400, color: 'var(--fg-1)' }}>{lbl}</span>
            </div>
          );
        })}
      </div>
    </div>
  );

  const fields = {
    hero: (
      <>
        <RadioGroup label="Style" options={HERO_STYLES} value={props.style ?? 0} onChange={v => set('style', v)} />
        <window.Input label="Headline text" value={props.headline || (persona.id === 'nour' ? 'Summer Edit' : 'Studio Series')} onChange={e => set('headline', e.target.value)} help="Short, punchy — 3 to 5 words." />
        <window.Input label="CTA button text" value={props.cta ?? 'Shop now →'} onChange={e => set('cta', e.target.value)} />
        <div>
          <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--fg-2)', marginBottom: 7 }}>Background image</div>
          <div style={{ height: 76, background: 'var(--sand-50)', borderRadius: 8, border: '2px dashed var(--hairline-bold)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', gap: 8, color: 'var(--fg-3)', fontSize: 12 }}>
            <i data-lucide="image-plus" style={{ width: 15, height: 15 }}></i> Upload image
          </div>
        </div>
      </>
    ),
    featured: (
      <>
        <RadioGroup label="Layout" options={LAYOUT_STYLES} value={props.layout ?? 0} onChange={v => set('layout', v)} />
        <window.Select label="Products per row" value={props.perRow ?? '2'} onChange={e => set('perRow', e.target.value)} options={['2', '3']} />
        <window.Select label="Max products shown" value={props.maxItems ?? '8'} onChange={e => set('maxItems', e.target.value)} options={['4', '6', '8', '12']} />
      </>
    ),
    collections: (
      <>
        <window.Select label="Display style" value={props.style ?? 'Grid'} onChange={e => set('style', e.target.value)} options={['Grid', 'Horizontal scroll', 'List']} />
        <window.Input label="Section title" value={props.title ?? 'Shop by category'} onChange={e => set('title', e.target.value)} />
      </>
    ),
    banner2: (
      <>
        <window.Input label="Promo headline" value={props.headline || (persona.id === 'nour' ? 'Ramadan special' : 'Limited time offer')} onChange={e => set('headline', e.target.value)} />
        <window.Input label="Discount code" value={props.code ?? 'SAVE20'} onChange={e => set('code', e.target.value)} help="Leave blank to hide the code badge." />
        <window.Input label="Button text" value={props.btnText ?? 'Claim offer →'} onChange={e => set('btnText', e.target.value)} />
      </>
    ),
    reviews: (
      <>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', background: 'var(--mint-tint)', borderRadius: 8, marginBottom: 4 }}>
          <i data-lucide="check-circle" style={{ width: 13, height: 13, color: 'var(--mint)', flexShrink: 0 }}></i>
          <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--mint-deep)' }}>Judge.me connected</span>
        </div>
        <window.Select label="Reviews to show" value={props.count ?? '3'} onChange={e => set('count', e.target.value)} options={['2', '3', '5', '10']} />
        <RadioGroup label="Product page placement" options={REVIEW_PLACEMENTS} value={props.placement ?? 'below_description'} onChange={v => set('placement', v)} />
        <window.Toggle checked={props.showRating ?? true} onChange={v => set('showRating', v)} label="Show star summary below title" />
      </>
    ),
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ padding: '14px 14px 10px', borderBottom: '1px solid var(--hairline)', flexShrink: 0 }}>
        <div style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--fg-3)', fontWeight: 500, marginBottom: 3 }}>Section</div>
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-1)' }}>{section.label}</div>
      </div>
      <div style={{ flex: 1, padding: '14px', display: 'flex', flexDirection: 'column', gap: 16, overflowY: 'auto' }}>
        {fields[section.id] || <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>No configurable properties.</div>}
      </div>
    </div>
  );
};

// ---- Main Editor Screen ----
const EditorScreen = ({ persona, tweaks }) => {
  const [sections, setSections] = React.useState(DEFAULT_SECTIONS);
  const [selectedId, setSelectedId] = React.useState(null);
  const [sectionProps, setSectionProps] = React.useState(DEFAULT_SECTION_PROPS);
  const [activeMobileTab, setActiveMobileTab] = React.useState('home');
  const [saved, setSaved] = React.useState(false);
  const { dark } = tweaks;

  const selectedSection = sections.find(s => s.id === selectedId) || null;

  const moveSection = (index, dir) => {
    const newSecs = [...sections];
    const ni = index + dir;
    if (ni < 0 || ni >= sections.length) return;
    [newSecs[index], newSecs[ni]] = [newSecs[ni], newSecs[index]];
    setSections(newSecs);
  };

  const toggleSection = (id) => {
    setSections(prev => prev.map(s => s.id === id ? { ...s, enabled: !s.enabled } : s));
  };

  const handlePropChange = (sectionId, key, value) => {
    setSectionProps(prev => ({ ...prev, [sectionId]: { ...(prev[sectionId] || {}), [key]: value } }));
  };

  const handleSave = () => {
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  };

  const cardBg = dark ? 'rgba(255,255,255,0.06)' : 'var(--white)';
  const cardBorder = dark ? 'rgba(255,255,255,0.1)' : 'var(--hairline)';
  const textColor = dark ? 'rgba(245,241,232,0.9)' : 'var(--fg-1)';
  const subColor = dark ? 'rgba(245,241,232,0.5)' : 'var(--fg-3)';

  const SCREEN_TABS = ['home', 'product', 'search', 'cart', 'account'];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      {/* Toolbar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16, flexWrap: 'wrap', flexShrink: 0 }}>
        <div>
          <div style={{ fontSize: 18, fontWeight: 600, color: textColor }}>App editor</div>
          <div style={{ fontSize: 12, color: subColor, marginTop: 1 }}>Reorder sections, toggle visibility, click to configure — preview updates live</div>
        </div>
        <div style={{ flex: 1 }}></div>
        <window.Button size="sm" icon={saved ? 'check' : 'save'} onClick={handleSave} style={{ minWidth: 110 }}>
          {saved ? 'Saved!' : 'Save changes'}
        </window.Button>
      </div>

      {/* Three-column layout */}
      <div style={{ display: 'grid', gridTemplateColumns: '216px 1fr 220px', gap: 14, flex: 1, minHeight: 0 }}>

        {/* LEFT: section list */}
        <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          <div style={{ padding: '12px 12px 8px', borderBottom: `1px solid ${cardBorder}`, flexShrink: 0 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: textColor }}>Home screen sections</div>
            <div style={{ fontSize: 10, color: subColor, marginTop: 1 }}>↑↓ reorder · toggle show/hide · click to edit</div>
          </div>
          <div style={{ flex: 1, padding: '6px 6px', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 2 }}>
            {sections.map((section, index) => (
              <SectionRow
                key={section.id} section={section} index={index} total={sections.length}
                onMove={moveSection} onToggle={toggleSection}
                onSelect={setSelectedId} selected={selectedId}
              />
            ))}
          </div>
          <div style={{ padding: '8px 6px', borderTop: `1px solid ${cardBorder}`, flexShrink: 0 }}>
            <button
              style={{ width: '100%', padding: '7px', borderRadius: 7, border: `1.5px dashed ${dark ? 'rgba(255,255,255,0.2)' : 'var(--hairline-bold)'}`, background: 'transparent', cursor: 'pointer', fontSize: 11, color: subColor, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5 }}
              onClick={() => {
                // Add a new promo banner if not already present, else toggle existing
                const existingIndex = sections.findIndex(s => s.id === 'banner2');
                if (existingIndex >= 0) {
                  toggleSection('banner2');
                  setSelectedId('banner2');
                }
              }}>
              <i data-lucide="plus" style={{ width: 12, height: 12 }}></i> Add section
            </button>
          </div>
        </div>

        {/* CENTER: phone preview */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14, minHeight: 0, overflow: 'auto' }}>
          {/* Screen tab switcher */}
          <div style={{ display: 'flex', gap: 3, background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 999, padding: 3, flexShrink: 0 }}>
            {SCREEN_TABS.map(t => (
              <button key={t} onClick={() => setActiveMobileTab(t)} style={{ padding: '5px 13px', borderRadius: 999, fontSize: 11, fontWeight: activeMobileTab === t ? 500 : 400, background: activeMobileTab === t ? 'var(--ink)' : 'transparent', color: activeMobileTab === t ? 'var(--paper)' : textColor, border: 'none', cursor: 'pointer', transition: 'all 140ms var(--ease)', textTransform: 'capitalize' }}>
                {t}
              </button>
            ))}
          </div>

          {/* Live phone preview */}
          <window.MobileApp
            persona={persona}
            sections={sections}
            sectionProps={sectionProps}
            scale={0.95}
            externalTab={activeMobileTab}
            onTabChange={setActiveMobileTab}
          />

          {/* Uniqueness score */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 11, color: subColor, flexShrink: 0 }}>
            <i data-lucide="shield-check" style={{ width: 13, height: 13, color: 'var(--mint)' }}></i>
            <span>Uniqueness score: <strong style={{ color: 'var(--mint)' }}>78%</strong> · ✓ Above Apple 4.2 threshold</span>
          </div>
        </div>

        {/* RIGHT: properties panel */}
        <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
          <PropertiesPanel
            section={selectedSection}
            sectionProps={sectionProps}
            onPropChange={handlePropChange}
            persona={persona}
          />
        </div>
      </div>
    </div>
  );
};

window.EditorScreen = EditorScreen;
