/* global React, ReactDOM */
// Skillzip Prototype v2 — App Shell
// Changes vs v1: A5 and A8 removed from ALL_SCREENS (merged into A2/A9)
const { useState, useEffect, useCallback } = React;
const { ProtoSidebar, ProtoTopbar, Icon } = window;

const ALL_SCREENS = [
  { key: 'S1',  group: 'Sell a skill',  title: 'Create skill entry'    },
  { key: 'A1',  group: 'Upload skill',  title: 'Upload files'          },
  { key: 'A2',  group: 'Upload skill',  title: 'Validate & Scan'       },
  { key: 'A7',  group: 'Upload skill',  title: 'Fix issues'            },
  { key: 'A9',  group: 'Upload skill',  title: 'Preview listing'       },
  { key: 'A13', group: 'Upload skill',  title: 'Publish'               },
  { key: 'A14', group: 'Upload skill',  title: 'Publish success'       },
  { key: 'B1',  group: 'Create skill',  title: 'Create from expertise' },
  { key: 'B2',  group: 'Create skill',  title: 'Start here'            },
  { key: 'B3',  group: 'Create skill',  title: 'Open Claude'           },
  { key: 'B4',  group: 'Create skill',  title: 'Upload to Claude'      },
  { key: 'B5',  group: 'Create skill',  title: 'Copy prompt'           },
  { key: 'B6',  group: 'Create skill',  title: 'Answer questions'      },
  { key: 'B7',  group: 'Create skill',  title: 'Download files'        },
  { key: 'B8',  group: 'Create skill',  title: 'Upload back'           },
];

const ALL_KEYS = ALL_SCREENS.map(s => s.key);

const SECTION_KEYS = ['publish', 'grow', 'earn', 'connect'];
const ALL_VALID    = [...ALL_KEYS, ...SECTION_KEYS];

const SECTION_META = {
  publish: { title: 'Publish',  description: 'Manage your listing, set pricing, and preview how buyers see your skill.', icon: 'send' },
  grow:    { title: 'Grow',     description: 'Track performance, see where your traffic comes from, and get tips to improve sales.', icon: 'trending-up' },
  earn:    { title: 'Earn',     description: 'View revenue, payout history, and download tax documents.', icon: 'dollar-sign' },
  connect: { title: 'Connect',  description: 'Join the expert community and get support from the Skillzip team.', icon: 'users' },
};

function useHashNav() {
  const getKey = () => {
    const h = (window.location.hash || '#S1').slice(1);
    return ALL_VALID.includes(h) ? h : 'S1';
  };
  const [key, setKey] = useState(getKey);

  useEffect(() => {
    const onHash = () => setKey(getKey());
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  const nav = useCallback((k) => {
    if (ALL_VALID.includes(k)) {
      window.location.hash = '#' + k;
      setKey(k);
      try {
        window.parent && window.parent.postMessage({ type: 'skillzip:navigate', key: k }, window.location.origin);
      } catch (e) {}
      const content = document.querySelector('.proto-content');
      if (content) content.scrollTop = 0;
    }
  }, []);

  return [key, nav];
}

function ComingSoonScreen({ sectionKey }) {
  const meta = SECTION_META[sectionKey];
  if (!meta) return null;
  return (
    <div className="screen-wrap screen-enter">
      <div style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        justifyContent: 'center', padding: '72px 32px',
        textAlign: 'center', maxWidth: 480, margin: '0 auto',
      }}>
        <div style={{
          width: 64, height: 64, borderRadius: 'var(--radius-lg)',
          background: 'var(--color-bg-elevated)', border: '1px solid var(--color-border-subtle)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: 24, boxShadow: 'var(--shadow-sm)',
        }}>
          <Icon name={meta.icon} size={28} color="var(--color-text-tertiary)" />
        </div>
        <span style={{
          display: 'inline-block', fontSize: 10.5, fontWeight: 600,
          letterSpacing: '0.08em', textTransform: 'uppercase',
          color: 'var(--color-text-tertiary)', background: 'var(--color-bg-elevated)',
          border: '1px solid var(--color-border-subtle)', padding: '3px 10px',
          borderRadius: 'var(--radius-full)', marginBottom: 18,
        }}>Coming soon</span>
        <h1 style={{ fontSize: 28, fontWeight: 600, color: 'var(--color-text-primary)', letterSpacing: '-0.02em', lineHeight: 1.2, marginBottom: 10 }}>{meta.title}</h1>
        <p style={{ fontSize: 14, color: 'var(--color-text-secondary)', lineHeight: 1.6, maxWidth: 360 }}>{meta.description}</p>
      </div>
    </div>
  );
}

function App() {
  const [screen, nav] = useHashNav();

  const isComingSoon  = SECTION_KEYS.includes(screen);
  const activeSection = isComingSoon ? screen : 'create';

  const idx = ALL_KEYS.indexOf(screen);
  const cur = ALL_SCREENS[idx] || { group: '', title: '' };

  const crumbs = isComingSoon
    ? []
    : [cur.group, cur.title].filter(Boolean);

  useEffect(() => {
    if (isComingSoon) return;
    const onKey = (e) => {
      if (e.target.matches('input,textarea,select')) return;
      if (e.key === 'ArrowRight' && idx < ALL_KEYS.length - 1) nav(ALL_KEYS[idx + 1]);
      if (e.key === 'ArrowLeft'  && idx > 0)                   nav(ALL_KEYS[idx - 1]);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [idx, nav, isComingSoon]);

  const Screens    = window.SCREENS || {};
  const ScreenComp = Screens[screen];

  return (
    <div className="proto-app">
      <ProtoSidebar current={screen} activeSection={activeSection} nav={nav} />
      <div className="proto-main">
        <ProtoTopbar
          crumbs={crumbs}
          onPrev={() => !isComingSoon && idx > 0 && nav(ALL_KEYS[idx - 1])}
          onNext={() => !isComingSoon && idx < ALL_KEYS.length - 1 && nav(ALL_KEYS[idx + 1])}
          idx={idx}
          total={ALL_KEYS.length}
          hideNav={isComingSoon}
          section={activeSection}
        />
        <div className="proto-content">
          {isComingSoon
            ? <ComingSoonScreen sectionKey={screen} />
            : ScreenComp
              ? <ScreenComp key={screen} nav={nav} />
              : (
                <div style={{ padding: 40, color: 'var(--color-text-tertiary)', fontSize: 14 }}>
                  Screen <code style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>{screen}</code> not implemented.
                </div>
              )
          }
        </div>
      </div>
    </div>
  );
}

window.__ProtoApp = App;
