// Sidebar rail + top header
const { useState } = React;

function Rail({ expanded, setExpanded, page, minimal }) {
  return (
    <aside className="rail">
      <div className="rail-logo">
        <div className="rail-logo-mark">
          <IconLogo />
        </div>
        <div className="rail-logo-text">Tools</div>
      </div>

      <a className={`rail-item ${page === 'home' ? 'active' : ''}`} href="/">
        <IconHome />
        <span className="rail-item-label">Home</span>
      </a>
      <a className={`rail-item ${page === 'shots' ? 'active' : ''}`} href="/shot-list/">
        <IconShotList />
        <span className="rail-item-label">Shot Lists</span>
      </a>
      <a className={`rail-item ${page === 'converter' ? 'active' : ''}`} href="/converter/">
        <IconImage />
        <span className="rail-item-label">Image Converter</span>
      </a>
      <a className={`rail-item ${page === 'invoice' ? 'active' : ''}`} href="/invoice/">
        <IconInvoice />
        <span className="rail-item-label">Invoices</span>
      </a>

      <div className="rail-spacer" />
      <button
        className="rail-toggle"
        onClick={() => setExpanded(!expanded)}
        aria-label={expanded ? 'Collapse' : 'Expand'}
        title={expanded ? 'Collapse' : 'Expand'}
      >
        <IconChevDouble />
      </button>
    </aside>
  );
}

function ThemeToggle({ theme, setTheme }) {
  return (
    <button
      className="theme-toggle"
      onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
      aria-label="Toggle theme"
      title={`Switch to ${theme === 'dark' ? 'light' : 'dark'} mode`}
    >
      <IconMoon className="icon-moon" />
      <IconSun className="icon-sun" />
    </button>
  );
}

function Header({ theme, setTheme, crumbs, minimal }) {
  const trail = crumbs || ['Projects', 'Aurora Active', 'Run the City — Shot List'];
  const ent = (typeof window.useEntitlement === 'function') ? window.useEntitlement() : { solo: true };
  return (
    <header className="header">
      <a className="site-title" href="/">Jump Studio</a>
      <span className="site-title-divider" />
      <div className="crumbs">
        {trail.map((c, i) => {
          // A crumb is either a plain string or { label, href }.
          const label = typeof c === 'string' ? c : c.label;
          const href  = typeof c === 'string' ? null : c.href;
          const isLast = i === trail.length - 1;
          return (
            <React.Fragment key={i}>
              {i > 0 && <span className="crumb-sep">/</span>}
              {href && !isLast
                ? <a className="crumb-link" href={href}>{label}</a>
                : <span className={isLast ? 'crumb-active' : ''}>{label}</span>}
            </React.Fragment>
          );
        })}
      </div>
      <div className="header-spacer" />
      <div className="header-actions">
        {!ent.solo && typeof window.ppOpenPlans === 'function' && (
          <button className="btn go-pro-btn" onClick={() => window.ppOpenPlans()}>
            {window.IconBolt ? <window.IconBolt /> : null} Go Pro
          </button>
        )}
        <ThemeToggle theme={theme} setTheme={setTheme} />
        {/* AuthControls comes from /auth.jsx — sign-in button when logged
            out, avatar-menu (with Sign out) when logged in. Backed by the
            same Supabase project the image converter uses. */}
        {typeof window.AuthControls === 'function' && <window.AuthControls />}
      </div>
    </header>
  );
}

// Share-nodes glyph for the "Create share link" button (kept local so we don't
// touch icons.jsx).
const IconShare = (props) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...props}>
    <circle cx="18" cy="5" r="3" />
    <circle cx="6" cy="12" r="3" />
    <circle cx="18" cy="19" r="3" />
    <path d="M8.6 13.5l6.8 4M15.4 6.5l-6.8 4" />
  </svg>
);

// `onShare` is optional — the editor passes it to surface the "Create share
// link" button next to the approval chip; the reviewer's own subheader omits
// it, so the button never appears there.
function ProjectSubheader({ shotCount, approvedCount, project, onShare }) {
  const pct = shotCount === 0 ? 0 : Math.round((approvedCount / shotCount) * 100);
  return (
    <div className="subheader">
      <div className="subheader-left">
        <div className="subheader-eyebrow">
          <span className="dot" /> {project.kind || 'Commercial'}
        </div>
        <h1>{project.title}</h1>
        <div className="subheader-meta">
          {(() => {
            const crew = project.crew || {};
            const items = [];
            const labels = { director: 'Director', dop: 'DoP', production: 'Production', agency: 'Agency' };
            ['director', 'dop', 'production', 'agency'].forEach(k => {
              if (crew[k]) items.push(<span key={k}><strong>{labels[k]}</strong> {crew[k]}</span>);
            });
            if (project.dates) items.push(<span key="dates"><strong>Shoot</strong> {project.dates}</span>);
            const fmts = (project.formats || []).filter(Boolean);
            if (fmts.length) {
              items.push(<span key="formats"><strong>{fmts.length === 1 ? 'Format' : 'Formats'}:</strong> {fmts.join(', ')}</span>);
            }
            return items.flatMap((node, i) => i === 0 ? [node] : [<span key={'s'+i} className="sep">·</span>, node]);
          })()}
        </div>
      </div>
      <div className="subheader-right">
        <a className="btn" href="/shot-list/"><IconFolder /> Projects Manager</a>
        {onShare && (
          <button className="btn btn-primary" onClick={onShare} title="Create a read-only review link to share">
            <IconShare /> Create share link
          </button>
        )}
        <div className="progress-chip" title={`${approvedCount} of ${shotCount} approved`}>
          <div className="progress-track">
            <div className="progress-fill" style={{ width: `${pct}%` }} />
          </div>
          <span><strong style={{color:'var(--text)'}}>{approvedCount}</strong>/{shotCount} approved</span>
        </div>
      </div>
    </div>
  );
}

function ProjectDetailsModal({ project, onSave, onClose }) {
  const [form, setForm] = React.useState({
    title: project.title,
    kind: project.kind,
    dates: project.dates,
    crew: { director: '', dop: '', production: '', agency: '', ...(project.crew || {}) },
    formats: [...project.formats],
  });
  const upd = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const updCrew = (k, v) => setForm(f => ({ ...f, crew: { ...f.crew, [k]: v } }));
  const updFormat = (i, v) => setForm(f => ({ ...f, formats: f.formats.map((x, xi) => xi === i ? v : x) }));
  const addFormat = () => setForm(f => f.formats.length < 4 ? { ...f, formats: [...f.formats, ''] } : f);
  const rmFormat = (i) => setForm(f => ({ ...f, formats: f.formats.filter((_, fi) => fi !== i) }));

  const CREW_FIELDS = [
    { key: 'director',   label: 'Director',   placeholder: 'Director name' },
    { key: 'dop',        label: 'DoP',        placeholder: 'Director of photography' },
    { key: 'production', label: 'Production', placeholder: 'Production company' },
    { key: 'agency',     label: 'Agency',     placeholder: 'Creative agency' },
  ];

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal modal-wide" onClick={(e) => e.stopPropagation()}>
        <h2>Project details</h2>
        <p className="modal-sub">Edit your project metadata. Empty crew fields are hidden.</p>

        <div className="field-row">
          <div className="field" style={{flex: 2}}>
            <label>Project name</label>
            <input value={form.title} onChange={(e) => upd('title', e.target.value)} />
          </div>
          <div className="field">
            <label>Project type</label>
            <input value={form.kind} onChange={(e) => upd('kind', e.target.value)} placeholder="Commercial" />
          </div>
        </div>

        <div className="field">
          <label>Shoot dates</label>
          <input value={form.dates} onChange={(e) => upd('dates', e.target.value)} placeholder="May 18–20" />
        </div>

        <div className="field">
          <label>Crew</label>
          <div className="crew-grid">
            {CREW_FIELDS.map(cf => (
              <div key={cf.key} className="crew-cell">
                <span className="crew-cell-label">{cf.label}</span>
                <input
                  value={form.crew[cf.key]}
                  onChange={(e) => updCrew(cf.key, e.target.value)}
                  placeholder={cf.placeholder}
                />
              </div>
            ))}
          </div>
        </div>

        <div className="field">
          <label>Capture formats <span style={{color:'var(--text-4)', fontWeight:400, textTransform:'none', letterSpacing:0}}>· up to 4</span></label>
          <div className="repeater">
            {form.formats.map((f, i) => (
              <div key={i} className="repeater-row">
                <input value={f} onChange={(e) => updFormat(i, e.target.value)} placeholder="Arri Mini LF" style={{ flex: 1 }} />
                <button className="icon-btn" onClick={() => rmFormat(i)} title="Remove"><IconTrash /></button>
              </div>
            ))}
            {form.formats.length < 4 && (
              <button className="btn btn-ghost" onClick={addFormat}><IconPlus /> Add format</button>
            )}
          </div>
        </div>

        <div className="modal-actions">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary" onClick={() => { onSave(form); onClose(); }}>
            <IconCheck /> Save
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Rail, Header, ProjectSubheader, ProjectDetailsModal, ThemeToggle });
