// 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, headerLeft }) {
  const trail = crumbs || ['Tools', 'Invoice Generator'];
  // Show the breadcrumb only when there's something to say. The manager view
  // passes an empty trail (just the wordmark); the editor uses headerLeft.
  const showCrumbs = !headerLeft && trail.length > 0;
  const ent = (typeof window.useEntitlement === 'function') ? window.useEntitlement() : { solo: true };
  return (
    <header className="header">
      <a className="site-title" href="/">Jump Studio</a>
      {(headerLeft || showCrumbs) && <span className="site-title-divider" />}
      {headerLeft ? headerLeft : (showCrumbs &&
        <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 (loaded in index.html) — sign-in
            button when logged out, avatar menu when signed in. Falls back to a
            static badge if the auth script hasn't registered yet. */}
        {typeof window.AuthControls === 'function'
          ? <window.AuthControls />
          : <div className="avatar">JS</div>}
      </div>
    </header>
  );
}

function ProjectSubheader({ shotCount, approvedCount, project, onEditProject }) {
  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}
        </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>);
            (project.formats || []).forEach((f, i) => {
              if (f) items.push(<span key={'f'+i}><strong>{i === 0 ? 'Format' : `Fmt ${i+1}`}</strong> {f}</span>);
            });
            return items.flatMap((node, i) => i === 0 ? [node] : [<span key={'s'+i} className="sep">·</span>, node]);
          })()}
        </div>
      </div>
      <div className="subheader-right">
        <button className="btn" onClick={onEditProject}><IconEdit /> Project details</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 });
