const T = {
  teal:'var(--sitm-teal)', tealDim:'var(--sitm-teal-dim)', tealDeep:'var(--sitm-teal-deep)',
  navy:'var(--sitm-navy)', ink:'var(--sitm-text)', border:'var(--sitm-border)',
  dim:'var(--sitm-bg-light-dim)', head:'var(--sitm-font-heading)', body:'var(--sitm-font-body)'
};
function Icon({ name, size = 18, stroke = 1.8, style }) {
  const p = {
    home: <g><path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V21h14V9.5"/></g>,
    make: <g><path d="M12 3v18M3 12h18"/></g>,
    pdf: <g><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></g>,
    tpl: <g><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></g>,
    files: <g><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></g>,
    help: <g><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/></g>,
    x: <g><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></g>,
    check: <polyline points="20 6 9 17 4 12"/>,
    chevR: <polyline points="9 18 15 12 9 6"/>,
    chevL: <polyline points="15 18 9 12 15 6"/>,
    download: <g><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="3" x2="12" y2="15"/></g>,
    edit: <g><path d="M17 3a2.83 2.83 0 0 1 4 4L7.5 20.5 2 22l1.5-5.5z"/></g>,
    upload: <g><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></g>,
    search: <g><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></g>,
    msg: <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8z"/>,
    play: <polygon points="5 3 19 12 5 21 5 3"/>,
    redo: <g><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></g>,
    undo: <g><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></g>,
    spark: <g><path d="M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"/></g>,
    trash: <g><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></g>,
    folder: <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>,
    shapes: <g><circle cx="8" cy="8" r="5"/><rect x="13" y="13" width="8" height="8" rx="1.5"/></g>,
    gear: <g><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></g>
  }[name];
  return <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" style={{flex:'none',...style}}>{p}</svg>;
}
function Btn({ kind = 'primary', size = 'md', icon, children, onClick, style, disabled }) {
  const [h, setH] = React.useState(false);
  const pads = { sm:'7px 14px', md:'10px 20px', lg:'14px 28px' };
  const kinds = {
    primary: { background: disabled ? 'var(--sitm-teal-light)' : h ? T.tealDim : T.teal, color:'#fff', border:'1px solid transparent' },
    navy: { background: h ? 'var(--sitm-navy-dark)' : T.navy, color:'#fff', border:'1px solid transparent' },
    ghost: { background: h ? 'var(--sitm-text-a05)' : '#fff', color:T.ink, border:'1px solid '+T.border },
    quiet: { background: h ? 'var(--sitm-text-a05)' : 'transparent', color:T.tealDeep, border:'1px solid transparent' },
    danger: { background: h ? '#a80000' : 'var(--sitm-sale-text)', color:'#fff', border:'1px solid transparent' }
  };
  return <button disabled={disabled} onClick={onClick} onMouseEnter={()=>setH(true)} onMouseLeave={()=>setH(false)}
    style={{ fontFamily:T.body, fontWeight:600, fontSize: size==='lg'?15:13, letterSpacing:'0.02em', padding:pads[size],
      display:'inline-flex', alignItems:'center', gap:8, cursor:disabled?'default':'pointer', borderRadius:8,
      transition:'background .2s ease', ...kinds[kind], ...style }}>
    {icon && <Icon name={icon} size={size==='sm'?14:16}/>}{children}
  </button>;
}
function Chip({ children, tone = 'teal', style }) {
  const tones = { teal:{background:'rgba(97,189,183,.15)',color:T.tealDeep}, navy:{background:'rgba(36,34,83,.08)',color:T.navy}, gold:{background:'rgba(253,189,50,.2)',color:'#8a6410'} };
  return <span style={{fontFamily:T.body,fontSize:11,fontWeight:600,letterSpacing:'0.04em',textTransform:'uppercase',padding:'3px 8px',display:'inline-block',borderRadius:5,...tones[tone],...style}}>{children}</span>;
}
function Modal({ open, onClose, width = 520, children }) {
  if (!open) return null;
  return <div style={{position:'fixed',inset:0,zIndex:80,display:'flex',alignItems:'center',justifyContent:'center'}}>
    <div onClick={onClose} style={{position:'absolute',inset:0,background:'rgba(36,34,83,.35)'}}></div>
    <div style={{position:'relative',width,maxWidth:'92vw',maxHeight:'86vh',overflow:'auto',background:'#fff',boxShadow:'0 12px 40px rgba(12,12,29,.25)',padding:28,borderRadius:14}}>
      <button onClick={onClose} style={{position:'absolute',top:14,right:14,background:'none',border:'none',cursor:'pointer',color:T.ink,padding:4}}><Icon name="x" size={18}/></button>
      {children}
    </div>
  </div>;
}
function H2({ children, style }) { return <div style={{fontFamily:T.head,fontSize:22,color:T.navy,lineHeight:1.15,...style}}>{children}</div>; }
function Sub({ children, style }) { return <div style={{fontSize:13.5,lineHeight:1.55,color:T.ink,...style}}>{children}</div>; }

const NAV = [
  { id:'home', label:'Home', icon:'home' },
  { id:'create', label:'Make materials', icon:'make' },
  { id:'pdfpick', label:'Edit a PDF', icon:'pdf' },
  { id:'pdfimport', label:'Import PDF', icon:'upload' },
  { id:'templates', label:'Templates', icon:'tpl' },
  { id:'elements', label:'Elements', icon:'shapes' },
  { id:'files', label:'My files', icon:'files' }
];
function TopNav({ active, onNav, onHelp, onSettings }) {
  const [hov, setHov] = React.useState(null);
  return <header id="cs-nav" style={{background:'#fff',borderBottom:'1px solid '+T.border,position:'sticky',top:0,zIndex:40}}>
    <div style={{maxWidth:1240,margin:'0 auto',padding:'0 28px',display:'flex',alignItems:'center',gap:32,height:64}}>
      <div style={{display:'flex',alignItems:'center',gap:12,cursor:'pointer'}} onClick={()=>onNav('home')}>
        <img src="./assets/sitm-logo.png" alt="" style={{width:40,height:40}}/>
        <div>
          <div style={{fontSize:9.5,fontWeight:600,letterSpacing:'0.12em',textTransform:'uppercase',color:T.tealDeep}}>Sonographer in the Making</div>
          <div style={{fontFamily:T.head,fontSize:17,color:T.navy,lineHeight:1.1}}>Content Studio</div>
        </div>
      </div>
      <nav style={{display:'flex',gap:4,flex:1}}>
        {NAV.map(n => {
          const on = active === n.id || (active==='editor' && n.id==='create');
          return <button key={n.id} onClick={()=>onNav(n.id)} onMouseEnter={()=>setHov(n.id)} onMouseLeave={()=>setHov(null)}
            style={{display:'flex',alignItems:'center',gap:7,fontFamily:T.body,fontSize:13.5,fontWeight:on?600:500,color:on?T.tealDeep:T.ink,
              background:hov===n.id&&!on?'var(--sitm-text-a05)':'transparent',border:'none',cursor:'pointer',padding:'8px 13px',
              boxShadow:on?'inset 0 -3px 0 var(--sitm-teal)':'none',height:64,boxSizing:'border-box'}}>
            <Icon name={n.icon} size={16}/>{n.label}
          </button>;
        })}
      </nav>
      <button title="Settings" onClick={onSettings} style={{display:'flex',alignItems:'center',background:active==='settings'?'rgba(97,189,183,.12)':'none',border:'1px solid '+(active==='settings'?'var(--sitm-teal)':T.border),padding:'8px 10px',cursor:'pointer',color:active==='settings'?T.tealDeep:T.ink,borderRadius:8}}><Icon name="gear" size={16}/></button>
      <button id="cs-help-btn" onClick={onHelp} style={{display:'flex',alignItems:'center',gap:7,background:'none',border:'1px solid '+T.border,padding:'8px 14px',cursor:'pointer',borderRadius:8,fontFamily:T.body,fontSize:13,fontWeight:500,color:T.ink}}>
        <Icon name="help" size={15}/>Help
      </button>
      <div style={{display:'flex',alignItems:'center',gap:8}}>
        <div style={{width:32,height:32,borderRadius:'50%',background:T.navy,color:'#fff',display:'flex',alignItems:'center',justifyContent:'center',fontSize:12,fontWeight:600}}>J</div>
        <span style={{fontSize:13,fontWeight:500}}>Jenny</span>
      </div>
    </div>
  </header>;
}
function HelpMenu({ open, onClose, onAction }) {
  if (!open) return null;
  const items = [
    { id:'tour', icon:'play', label:'Show me around', sub:'A one minute walk through the studio' },
    { id:'what', icon:'spark', label:'What can I make here?', sub:'The kinds of materials and how they save' },
    { id:'templates', icon:'tpl', label:'How templates work', sub:'Looks, and adding your own from a PDF' },
    { id:'feedback', icon:'msg', label:'Send feedback', sub:'Tell Keith what is confusing or broken' }
  ];
  return <div style={{position:'fixed',inset:0,zIndex:70}} onClick={onClose}>
    <div onClick={e=>e.stopPropagation()} style={{position:'absolute',top:70,right:120,width:320,background:'#fff',border:'1px solid '+T.border,boxShadow:'0 8px 30px rgba(12,12,29,.15)',borderRadius:12,overflow:'hidden'}}>
      {items.map(it => <button key={it.id} onClick={()=>onAction(it.id)}
        style={{display:'flex',gap:12,alignItems:'flex-start',width:'100%',textAlign:'left',background:'none',border:'none',borderBottom:'1px solid '+T.border,padding:'13px 16px',cursor:'pointer',fontFamily:T.body}}>
        <span style={{color:T.tealDeep,marginTop:1}}><Icon name={it.icon} size={16}/></span>
        <span><span style={{display:'block',fontSize:13.5,fontWeight:600,color:T.navy}}>{it.label}</span>
        <span style={{display:'block',fontSize:12,color:T.ink,marginTop:2}}>{it.sub}</span></span>
      </button>)}
    </div>
  </div>;
}
function FeedbackFab({ onClick }) {
  const [h,setH] = React.useState(false);
  return <button id="cs-feedback" onClick={onClick} onMouseEnter={()=>setH(true)} onMouseLeave={()=>setH(false)}
    style={{position:'fixed',right:24,bottom:24,zIndex:60,display:'flex',alignItems:'center',gap:8,background:h?'var(--sitm-navy-dark)':T.navy,color:'#fff',
      border:'none',padding:'12px 18px',cursor:'pointer',fontFamily:T.body,fontSize:13,fontWeight:600,boxShadow:'0 4px 16px rgba(12,12,29,.25)',borderRadius:10,transition:'background .2s ease'}}>
    <Icon name="msg" size={15}/>Feedback
  </button>;
}
function FeedbackModal({ open, onClose }) {
  const [about,setAbout] = React.useState('This page');
  const [text,setText] = React.useState('');
  const [sent,setSent] = React.useState(false);
  React.useEffect(()=>{ if(open){setSent(false);setText('');} },[open]);
  return <Modal open={open} onClose={onClose} width={480}>
    {sent ? <div style={{textAlign:'center',padding:'24px 0'}}>
      <div style={{width:52,height:52,margin:'0 auto 14px',background:'rgba(97,189,183,.18)',display:'flex',alignItems:'center',justifyContent:'center',color:T.tealDeep,borderRadius:'50%'}}><Icon name="check" size={26} stroke={2.2}/></div>
      <H2 style={{fontSize:20}}>Thank you</H2>
      <Sub style={{marginTop:8}}>Your note went to Keith. It helps more than you think.</Sub>
      <Btn style={{marginTop:20}} onClick={onClose}>Done</Btn>
    </div> : <div>
      <H2 style={{fontSize:20}}>Send feedback</H2>
      <Sub style={{marginTop:6,marginBottom:18}}>Anything counts. A confusing button, a wish, something that looks off.</Sub>
      <div style={{fontSize:12.5,fontWeight:600,marginBottom:8}}>What is this about?</div>
      <div style={{display:'flex',gap:8,marginBottom:16}}>
        {['This page','Something I made','An idea'].map(o => <button key={o} onClick={()=>setAbout(o)}
          style={{fontFamily:T.body,fontSize:12.5,fontWeight:500,padding:'7px 12px',cursor:'pointer',borderRadius:7,border:'1px solid '+(about===o?T.teal:T.border),background:about===o?'rgba(97,189,183,.12)':'#fff',color:about===o?T.tealDeep:T.ink}}>{o}</button>)}
      </div>
      <textarea value={text} onChange={e=>setText(e.target.value)} placeholder="Write it the way you would text it"
        style={{width:'100%',boxSizing:'border-box',height:110,padding:12,fontFamily:T.body,fontSize:13.5,color:T.ink,border:'1px solid rgba(62,71,97,.2)',resize:'vertical',outline:'none',borderRadius:8}}/>
      <div style={{display:'flex',justifyContent:'flex-end',gap:10,marginTop:16}}>
        <Btn kind="ghost" onClick={onClose}>Cancel</Btn>
        <Btn disabled={!text.trim()} onClick={()=>setSent(true)}>Send</Btn>
      </div>
    </div>}
  </Modal>;
}
function DeleteBtn({ onClick, title }) {
  const [h,setH] = React.useState(false);
  return <button title={title||'Delete'} onClick={(e)=>{e.stopPropagation();onClick();}} onMouseEnter={()=>setH(true)} onMouseLeave={()=>setH(false)}
    style={{background:h?'rgba(194,0,0,.08)':'transparent',border:'1px solid '+(h?'var(--sitm-sale-text)':T.border),color:h?'var(--sitm-sale-text)':T.ink,
      cursor:'pointer',padding:'6px 8px',borderRadius:8,display:'inline-flex',alignItems:'center',transition:'all .15s ease'}}>
    <Icon name="trash" size={14}/>
  </button>;
}
function ConfirmDeleteModal({ item, onCancel, onConfirm }) {
  return <Modal open={!!item} onClose={onCancel} width={440}>
    {item && <div>
      <H2 style={{fontSize:20}}>Delete this?</H2>
      <Sub style={{marginTop:10}}><b>{item.name}</b> will be gone for good. There is no undo.</Sub>
      <div style={{display:'flex',justifyContent:'flex-end',gap:10,marginTop:22}}>
        <Btn kind="ghost" onClick={onCancel}>Keep it</Btn>
        <Btn kind="danger" icon="trash" onClick={onConfirm}>Delete</Btn>
      </div>
    </div>}
  </Modal>;
}
function Toast({ msg }) {
  if (!msg) return null;
  return <div style={{position:'fixed',bottom:24,left:'50%',transform:'translateX(-50%)',zIndex:90,background:T.navy,color:'#fff',padding:'12px 22px',fontFamily:T.body,fontSize:13.5,fontWeight:500,boxShadow:'0 6px 20px rgba(12,12,29,.3)',borderRadius:10,display:'flex',alignItems:'center',gap:10}}>
    <span style={{color:'var(--sitm-teal)'}}><Icon name="check" size={16} stroke={2.4}/></span>{msg}
  </div>;
}
// Guided tour: dims the page, outlines one element at a time
const TOUR_STEPS = [
  { target:'cs-nav', title:'Five tabs, five jobs', body:'Everything in the studio lives in these tabs. Home shows your shortcuts, and you can jump between tools any time. Nothing here has an order you have to follow.' },
  { target:'tool-create', title:'Make materials', body:'This is the big one. Pick what you want to make, pick a look, pick questions from your bank, and the studio builds it for you.' },
  { target:'tool-pdf', title:'Edit a PDF', body:'Open any of your existing PDFs and edit it right on the page, like a document. Save it back as a PDF when you are done.' },
  { target:'tool-templates', title:'Templates', body:'Templates are the looks your materials come out in. Browse the built in ones, or add your own from any PDF and reuse it whenever you like.' },
  { target:'tool-elements', title:'Elements', body:'Little pieces you can drop onto any page: header bands, waves, word art, your logo. Save your own from the editor and build up a library that is all yours.' },
  { target:'tool-files', title:'My files', body:'Everything you make lands here. Come back any time to download a file again or open it in the editor and keep working on it.' },
  { target:'home-types', title:'What you can make today', body:'These are the material types that work right now. Each one tells you how it saves. More are coming, and this list will grow.' },
  { target:'cs-feedback', title:'Tell us everything', body:'This button is on every page. If something is confusing or you wish it worked differently, send a note. Keith reads all of it.' }
];
function Tour({ active, onDone }) {
  const [step, setStep] = React.useState(0);
  const [rect, setRect] = React.useState(null);
  React.useEffect(()=>{ if(active) setStep(0); },[active]);
  React.useEffect(()=>{
    if (!active) return;
    const el = document.getElementById(TOUR_STEPS[step].target);
    if (el) {
      const r = el.getBoundingClientRect();
      if (r.top < 0 || r.bottom > window.innerHeight) window.scrollTo({top: window.scrollY + r.top - 120, behavior:'smooth'});
      const t = setTimeout(()=>{ const r2 = el.getBoundingClientRect(); setRect({top:r2.top,left:r2.left,width:r2.width,height:r2.height}); }, 320);
      return ()=>clearTimeout(t);
    }
  },[active, step]);
  if (!active || !rect) return null;
  const s = TOUR_STEPS[step];
  const below = rect.top + rect.height + 190 < window.innerHeight;
  const cardTop = below ? rect.top + rect.height + 14 : Math.max(14, rect.top - 196);
  const cardLeft = Math.min(Math.max(16, rect.left + rect.width/2 - 180), window.innerWidth - 380);
  return <div style={{position:'fixed',inset:0,zIndex:100}}>
    <div style={{position:'absolute',inset:0,background:'rgba(12,12,29,.45)'}}></div>
    <div style={{position:'fixed',top:rect.top-6,left:rect.left-6,width:rect.width+12,height:rect.height+12,background:'transparent',outline:'3px solid var(--sitm-teal)',boxShadow:'0 0 0 9999px rgba(12,12,29,.45)',borderRadius:12,pointerEvents:'none'}}></div>
    <div style={{position:'fixed',top:cardTop,left:cardLeft,width:360,background:'#fff',padding:22,boxShadow:'0 10px 36px rgba(12,12,29,.35)',borderRadius:14,fontFamily:'var(--sitm-font-body)'}}>
      <div style={{fontSize:11,fontWeight:600,letterSpacing:'0.08em',textTransform:'uppercase',color:'var(--sitm-teal-deep)',marginBottom:6}}>{step+1} of {TOUR_STEPS.length}</div>
      <div style={{fontFamily:'var(--sitm-font-heading)',fontSize:18,color:'var(--sitm-navy)',marginBottom:8}}>{s.title}</div>
      <div style={{fontSize:13,lineHeight:1.55,color:'var(--sitm-text)'}}>{s.body}</div>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginTop:18}}>
        <Btn kind="quiet" size="sm" onClick={onDone}>Skip</Btn>
        <div style={{display:'flex',gap:8}}>
          {step > 0 && <Btn kind="ghost" size="sm" onClick={()=>setStep(step-1)}>Back</Btn>}
          {step < TOUR_STEPS.length-1
            ? <Btn size="sm" onClick={()=>setStep(step+1)}>Next</Btn>
            : <Btn size="sm" onClick={onDone}>Got it</Btn>}
        </div>
      </div>
    </div>
  </div>;
}
Object.assign(window, { T, Icon, Btn, Chip, Modal, H2, Sub, TopNav, HelpMenu, FeedbackFab, FeedbackModal, Toast, Tour, DeleteBtn, ConfirmDeleteModal });
