// Opsmera AI — the co-pilot. Reads everything in the system (deadlines, invoices,
// intake, jobs, meetings, predictive signals) and hands each stakeholder their
// ranked next-best-actions, matched to their role. Suggestions cite the records
// they came from, so it's audit-able, not a black box.
const CAT_STYLE = {
  compliance: { bg: 'var(--tint-urgent)', fg: '#f0938a', icon: 'shield-alert' },
  invoice:    { bg: 'var(--tint-warning)', fg: '#f0cd82', icon: 'receipt' },
  predictive: { bg: 'var(--tint-violet)', fg: '#c3b9f7', icon: 'activity' },
  meeting:    { bg: 'var(--tint-info)', fg: '#9dc2f7', icon: 'gavel' },
  saving:     { bg: 'var(--tint-resolved)', fg: '#7fe9c2', icon: 'piggy-bank' },
  field:      { bg: 'var(--tint-info)', fg: '#9dc2f7', icon: 'mic' },
};

const SUGGESTIONS = [
  { cat: 'compliance', impact: 'high', impactLabel: 'High exposure',
    title: 'Clear the Adelaide Central emergency-lighting breach today',
    why: 'It is 3 days overdue at $4,000/week exposure - your single largest live risk. Sparke\'s $760 quote is approved by the chair but the treasurer denied it pending the compliance certificate. Attach the AS 2293 cert and it can be re-sent and dispatched in one step.',
    src: ['Compliance · AS 2293', 'INV-20412', 'Adelaide Central'],
    basis: 'Once the cert is attached, this treasurer has approved within the hour on 3 prior occasions; overdue lighting at this site drew a council notice last year.',
    actions: [['Attach cert & re-send', 'paperclip', 'primary'], ['Open building', 'arrow-right', 'ghost']],
    roles: ['strata', 'treasurer'] },
  { cat: 'invoice', impact: 'med', impactLabel: 'Unblocks payment run',
    title: 'Two invoices are one tap from Friday\'s payment run',
    why: 'INV-20415 (Otis, $3,400) has reached majority and only needs filing. INV-20418 (ASE Fire, $2,200) is waiting on your approval and matches the approved panel-repair quote - no duplicate found. Approving both clears $5,600 for this run.',
    src: ['Invoice hub', 'INV-20415', 'INV-20418'],
    basis: 'Both creditors\' quotes have landed within 3% of approved on 5 past jobs; you usually clear matched invoices in under a day.',
    actions: [['Review & approve', 'check', 'primary'], ['Open invoices', 'arrow-right', 'ghost']],
    roles: ['strata', 'treasurer'] },
  { cat: 'predictive', impact: 'med', impactLabel: 'Prevents failure',
    title: 'Pre-empt the Cove Apartments HVAC failure',
    why: 'The Level 7 condenser is trending to failure within 30 days (87% confidence). A preventive work order is raised and the treasurer asked for a second quote before approving Cool-Air\'s $1,840 - add a comparison quote to keep it moving before the unit fails in summer.',
    src: ['Predictive · HVAC', 'OPS-4815', 'INV-20417'],
    basis: 'The same condenser model failed at Cove 14 months ago; Cool-Air\'s last quote here ran 8% above two comparisons.',
    actions: [['Request 2nd quote', 'mail', 'primary'], ['View job', 'arrow-right', 'ghost']],
    roles: ['strata', 'maintenance', 'treasurer'] },
  { cat: 'meeting', impact: 'med', impactLabel: 'AGM in 10 days',
    title: 'Two AGM motions still need votes at Harbourview',
    why: 'Quorum is met (17 of 13), but the insurance renewal is close - 22 for, 19 against. Nudging the 41 lots who have not voted will give the committee a clear mandate before the AGM, and the fire-remediation motion is trending to carry.',
    src: ['Meetings · SP 84021', 'Motion 02', 'Motion 03'],
    basis: 'Your AGMs average 61% turnout; a single reminder nudge has lifted it by ~18 points at this scheme before.',
    actions: [['Nudge non-voters', 'send', 'primary'], ['Open meeting', 'arrow-right', 'ghost']],
    roles: ['strata'] },
  { cat: 'compliance', impact: 'high', impactLabel: 'Deadline in 6 days',
    title: 'Generate the AFSS logbook pack for The Lumen now',
    why: 'The annual statement is due for council lodgement in 6 days. All AS 1851 routines are current and evidenced, so I can assemble the compliant hardcopy pack and pre-fill the lodgement - you just review and sign.',
    src: ['Compliance · AFSS', 'The Lumen'],
    basis: 'Lodgement took 2 days on average last year; the two AFSS you left under 5 days both slipped past the date.',
    actions: [['Generate pack', 'printer', 'primary'], ['Open building', 'arrow-right', 'ghost']],
    roles: ['strata', 'building'] },
  { cat: 'field', impact: 'med', impactLabel: 'Closes the loop',
    title: 'Send a status update to the Unit 1203 resident',
    why: 'The water-ingress job logged by voice is now linked to Apex\'s warranty and awaiting re-inspection. The resident has not heard back since they reported it - a one-tap update closes the loop and prevents a follow-up call.',
    src: ['Intake · OPS-4820', 'The Lumen', 'Voice capture'],
    basis: 'Residents who get a status update within 24h are 70% less likely to log a follow-up call, on this portfolio.',
    actions: [['Send update', 'message-square', 'primary'], ['View thread', 'arrow-right', 'ghost']],
    roles: ['building', 'maintenance', 'strata'] },
  { cat: 'saving', impact: 'save', impactLabel: 'Saves ~$1,900/yr',
    title: 'Consolidate fire servicing across three NSW buildings',
    why: 'ASE Fire services Harbourview, Cove and Stirling on separate call-out rates. Bundling their AS 1851 routines into one portfolio agreement is projected to save about $1,900 a year and simplifies the audit trail to a single contract register entry.',
    src: ['Vendors · ASE Fire', '3 buildings', 'Contracts register'],
    basis: 'ASE\'s separate call-out fees across these 3 sites totalled ~$1,900 over the last 12 months versus a single bundled rate.',
    actions: [['Draft proposal', 'file-text', 'primary'], ['View vendor', 'arrow-right', 'ghost']],
    roles: ['strata', 'treasurer'] },
];

const ROLES = [['strata', 'Strata manager'], ['treasurer', 'Treasurer'], ['building', 'Building manager'], ['maintenance', 'Maintenance']];

function Suggestion({ s }) {
  const cs = CAT_STYLE[s.cat];
  return (
    <div className="sugg">
      <div className="rail" style={{ background: cs.bg, color: cs.fg }}><Icon name={cs.icon} /></div>
      <div>
        <div className="top">
          <h3>{s.title}</h3>
          <span className={`impact ${s.impact}`}>{s.impactLabel}</span>
        </div>
        <p className="why">{s.why}</p>
        {s.basis && <div className="sugg-basis"><Icon name="history" /><span>{s.basis}</span></div>}
        <div className="src">
          <span className="from">Read from</span>
          {s.src.map((r, i) => <span className="rec" key={i}>{r}</span>)}
        </div>
        <div className="act">
          {s.actions.map(([label, icon, kind], i) => (
            <button key={i} className={`btn ${kind === 'primary' ? 'btn-primary' : 'btn-ghost'} btn-sm`} onClick={() => runAiAction(label, icon)}><Icon name={icon} />{label}</button>
          ))}
        </div>
      </div>
    </div>
  );
}

function Assistant({ onNav, onBuilding, persona }) {
  const [role, setRole] = React.useState((persona && persona.id) || 'strata');
  const [q, setQ] = React.useState('');
  const globeRef = React.useRef(null);
  React.useEffect(() => { if (globeRef.current && window.OpsGlobe) window.OpsGlobe.init(globeRef.current); }, []);
  const list = SUGGESTIONS.filter(s => s.roles.includes(role));
  const pid = persona && persona.id;
  const examples =
    pid === 'maintenance' ? ['What is on the run sheet today?', 'Which AS 1851 routines are due this week?', 'Which jobs are missing photo sign-off?', 'Which crew is closest to Adelaide Central?']
    : pid === 'building'  ? ['What is open on site today?', 'Which residents are still waiting on an update?', 'Anything overdue on AS 1851?', 'Draft the resident notice for the lift outage']
    : pid === 'treasurer' ? ['Which invoices are sitting on me?', 'How are we tracking against budget?', 'What was approved at the last meeting?', 'Draft the treasurer’s report for the AGM']
    : ['What needs me before Friday?', 'Where am I most exposed?', 'Draft the AGM agenda', 'Which invoices can I pay?'];
  const askPlaceholder =
    pid === 'maintenance' ? 'Ask Opsmera anything about today’s run sheet...'
    : pid === 'building'  ? 'Ask Opsmera anything about The Lumen...'
    : pid === 'treasurer' ? 'Ask Opsmera anything about Harbourview...'
    : 'Ask Opsmera anything about your portfolio...';
  const ask = (text) => {
    const query = (text || q).trim();
    if (!query) return;
    setQ('');
    act('Opsmera AI is reading your portfolio…', { kind: 'auto', icon: 'sparkles', sub: '“' + query + '”' });
  };
  return (
    <div className="view">
      <div className="asst-hero">
        <canvas ref={globeRef} className="globe" data-ops-globe data-points="320" data-active="6"></canvas>
        <div className="z">
          <div className="eyebrow" style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><Icon name="sparkles" />Opsmera AI · {
            pid === 'treasurer' ? 'reads every dollar across your scheme'
            : pid === 'building' ? 'reads every ticket on your building'
            : pid === 'maintenance' ? 'reads every job on the run sheet'
            : 'reads your whole portfolio'
          }</div>
          <h1>Here is what I would do <em>next</em>, {persona && persona.name ? persona.name.split(' ')[0] : 'Jessica'}.</h1>
          <div className="sub">{
            pid === 'treasurer'
              ? 'I have read every invoice, motion and budget line at Harbourview - SP 84021 and ranked the calls waiting on you as treasurer. Each one cites the records it came from.'
            : pid === 'building'
              ? 'I have read every ticket, deadline and resident message at The Lumen - SP 67203 and ranked what to action on site today. Each one cites the records it came from.'
            : pid === 'maintenance'
              ? 'I have read every job, asset routine and certificate across your 6 crews on today and ordered the run sheet by site, drive time and SLA. Each one cites the records it came from.'
            : 'I have read every deadline, invoice, ticket, job and motion across your 127 schemes and ranked the actions that move the book forward - matched to your role. Each one cites the records it came from.'
          }</div>
          <form className="asst-ask" onSubmit={e => { e.preventDefault(); ask(); }}>
            <Icon name="sparkles" />
            <input placeholder={askPlaceholder} value={q} onChange={e => setQ(e.target.value)} />
            <button type="submit" className="asst-go" aria-label="Ask"><kbd>↵</kbd></button>
          </form>
          <div className="asst-chips">{examples.map(e => <span className="asst-chip" key={e} onClick={() => ask(e)}>{e}</span>)}</div>
        </div>
      </div>
      <div className="asst-bar">
        <span className="lab">Suggested for</span>
        <div className="seg">{ROLES.map(([k, l]) => <button key={k} className={k === role ? 'on' : ''} onClick={() => setRole(k)}>{l}</button>)}</div>
        <span className="lab" style={{ marginLeft: 'auto' }}>{list.length} suggestions · updated live</span>
      </div>
      <div className="sugg-list">
        {list.map((s, i) => <Suggestion key={i} s={s} />)}
      </div>
    </div>
  );
}
Object.assign(window, { Assistant });
