/* ============================================
   LEGAL & INFO PAGES
   About · Privacy · Terms · Contact
   ============================================ */

/* Shared style constants — used directly in each screen */
const LS_H2 = { fontSize: 16, fontWeight: 700, marginTop: 32, marginBottom: 8, color: 'var(--fg-0)' };
const LS_P  = { marginBottom: 12, color: 'var(--fg-1)', lineHeight: 1.8 };
const LS_LI = { marginBottom: 6, paddingLeft: 16, position: 'relative', color: 'var(--fg-1)' };

/* Plain shell wrapper — no render props, just children */
function LegalShell({ eyebrow, title, lastUpdated, onBack, backLabel, children }) {
  return (
    <div style={{ maxWidth: 720, margin: '0 auto', paddingBottom: 'var(--space-7)' }}>
      {onBack && (
        <button className="btn btn-glass btn-sm" style={{ marginBottom: 'var(--space-4)' }} onClick={onBack}>
          <Icon name="arrow-left" size={14} /> {backLabel || 'Back'}
        </button>
      )}
      <div className="glass" style={{ padding: 'var(--space-6)', marginBottom: 'var(--space-4)' }}>
        <div className="eyebrow">{eyebrow}</div>
        <h1 className="h1" style={{ fontSize: 36, marginTop: 8 }}>{title}</h1>
        {lastUpdated && (
          <div className="mono fg-3" style={{ fontSize: 11, marginTop: 10 }}>Last updated: {lastUpdated}</div>
        )}
      </div>
      <div className="glass" style={{ padding: 'var(--space-6)', lineHeight: 1.8, fontSize: 14 }}>
        {children}
      </div>
    </div>
  );
}

/* Small link row reused in sidebar footer + auth screen */
function FooterLinks({ onNavigate, style }) {
  const pages = [
    { k: 'about',   label: 'About'   },
    { k: 'privacy', label: 'Privacy' },
    { k: 'terms',   label: 'Terms'   },
    { k: 'contact', label: 'Contact' },
  ];
  const btnStyle = {
    background: 'none', border: 'none', cursor: 'pointer',
    color: 'var(--fg-3)', fontSize: 11,
    fontFamily: 'var(--font-mono)', padding: 0,
    transition: 'color 150ms',
  };
  return (
    <div className="row gap-3" style={{ flexWrap: 'wrap', ...style }}>
      {pages.map((p, i) => (
        <React.Fragment key={p.k}>
          {i > 0 && <span style={{ color: 'var(--fg-3)', fontSize: 11 }}>·</span>}
          <button
            style={btnStyle}
            onMouseEnter={e => e.currentTarget.style.color = 'var(--accent)'}
            onMouseLeave={e => e.currentTarget.style.color = 'var(--fg-3)'}
            onClick={() => onNavigate?.(p.k)}
          >
            {p.label}
          </button>
        </React.Fragment>
      ))}
    </div>
  );
}

/* ============================================
   ABOUT
   ============================================ */
function AboutScreen({ onBack, onNavigate }) {
  return (
    <div data-screen-label="About">
      <LegalShell eyebrow="The platform" title="About AI Music Studio" onBack={onBack} backLabel={onBack ? 'Back' : undefined}>
        <p style={{ ...LS_P, fontSize: 16, color: 'var(--fg-0)', fontWeight: 500 }}>
          AI Music Studio is a platform where human artistry and machine intelligence meet — showcasing original music created by, with, and alongside AI.
        </p>

        <h2 style={LS_H2}>Our Mission</h2>
        <p style={LS_P}>
          We believe the conversation about AI in music should happen <em>with</em> the music, not just around it. AI Music Studio gives listeners a front-row seat to that process — rate tracks, leave timestamped comments at the exact moment something moves you, build playlists, and share.
        </p>
        <p style={LS_P}>
          We're not hiding whether something is AI-made. Every track is tagged and traceable. We think transparency is the only honest way to do this.
        </p>

        <h2 style={LS_H2}>The Artist</h2>
        <p style={LS_P}>
          Every track on this platform is composed or co-composed by <strong>Sasha</strong> — singer, songwriter, and producer. Sasha works with state-of-the-art AI composition and vocal processing models to create music that couldn't exist any other way. Tracks are labelled by origin: <strong>human</strong> for pure human performance, <strong>ai</strong> for AI-generated compositions, and <strong>human+ai</strong> for true collaborations.
        </p>

        <h2 style={LS_H2}>The Technology</h2>
        <p style={LS_P}>
          Tracks are produced using a combination of neural audio synthesis models, large language model-assisted lyrics and arrangement, and traditional digital audio workstation production. The exact models vary per release and are noted in track metadata where available.
        </p>

        <h2 style={LS_H2}>The Platform</h2>
        <p style={LS_P}>
          AI Music Studio is built on Firebase (Google Cloud), uses React for the interface, and stores all user data — comments, playlists, ratings — in Firestore. We don't run ads. We don't sell your data. Revenue comes directly from listeners who want to support the project.
        </p>

        <h2 style={LS_H2}>Get in Touch</h2>
        <p style={LS_P}>
          Questions, press enquiries, DMCA notices, or just want to say something about a track?{' '}
          <button
            onClick={() => onNavigate?.('contact')}
            style={{ background: 'none', border: 'none', color: 'var(--accent)', cursor: 'pointer', fontSize: 'inherit', padding: 0, textDecoration: 'underline' }}
          >
            Contact us here.
          </button>
        </p>

        <div style={{ marginTop: 32, padding: '20px 24px', background: 'var(--bg-1)', borderRadius: 14, border: '1px solid var(--line)' }}>
          <div className="mono fg-3" style={{ fontSize: 11, letterSpacing: '0.06em' }}>© {new Date().getFullYear()} AI Music Studio · All rights reserved</div>
        </div>
      </LegalShell>
    </div>
  );
}

/* ============================================
   PRIVACY POLICY
   ============================================ */
function PrivacyScreen({ onBack }) {
  return (
    <div data-screen-label="Privacy Policy">
      <LegalShell eyebrow="Legal" title="Privacy Policy" lastUpdated="May 2026" onBack={onBack}>
        <p style={LS_P}>
          This Privacy Policy explains what information AI Music Studio ("we", "our", "us") collects, how we use it, and your rights regarding that information. By using the platform you agree to this policy.
        </p>

        <h2 style={LS_H2}>1. Information We Collect</h2>
        <p style={LS_P}><strong>Account information</strong> — When you sign in with Google, we receive your name, email address, and profile photo from Google. We store this in Firebase Firestore to power your account.</p>
        <p style={LS_P}><strong>Usage data</strong> — We store the playlists you create, the comments you post, and the star ratings you give. Your play history and liked tracks are stored in your browser's local storage and are not synced to our servers.</p>
        <p style={LS_P}><strong>Contact data</strong> — If you submit a contact form, we store your name, email, and message in Firestore to respond to your enquiry.</p>
        <p style={LS_P}><strong>Technical data</strong> — Standard web server logs (IP address, browser type, referring URL) are collected automatically by Firebase Hosting. We do not link these to your account.</p>

        <h2 style={LS_H2}>2. How We Use Your Information</h2>
        <ul style={{ paddingLeft: 0, listStyle: 'none', marginBottom: 12 }}>
          {[
            'To operate your account and provide the service',
            'To display your comments and playlists to other users',
            'To send you notifications you have opted into',
            'To moderate content and enforce our Terms of Use',
            'To respond to support and contact enquiries',
            'To understand aggregate usage patterns (no individual tracking)',
          ].map((item, i) => (
            <li key={i} style={LS_LI}>
              <span style={{ position: 'absolute', left: 0, color: 'var(--accent)' }}>·</span>
              {item}
            </li>
          ))}
        </ul>
        <p style={LS_P}>We do not sell, rent, or trade your personal information to any third party.</p>

        <h2 style={LS_H2}>3. Third-Party Services</h2>
        <p style={LS_P}>We use the following third-party services, each with their own privacy policies:</p>
        <ul style={{ paddingLeft: 0, listStyle: 'none', marginBottom: 12 }}>
          {[
            'Google Firebase — authentication, database, and hosting (policies.google.com/privacy)',
            'Google Fonts — typeface delivery (policies.google.com/privacy)',
          ].map((item, i) => (
            <li key={i} style={LS_LI}>
              <span style={{ position: 'absolute', left: 0, color: 'var(--accent)' }}>·</span>
              {item}
            </li>
          ))}
        </ul>

        <h2 style={LS_H2}>4. Cookies and Local Storage</h2>
        <p style={LS_P}>
          We use browser <strong>localStorage</strong> (not traditional cookies) to store your theme preference, liked tracks, play history, and trending snapshots. This data never leaves your device unless you are signed in, in which case your account data is synced to Firestore.
        </p>
        <p style={LS_P}>
          Firebase Authentication may set a session cookie to maintain your sign-in state. This is strictly necessary for the service to function and cannot be disabled if you wish to remain logged in.
        </p>

        <h2 style={LS_H2}>5. Data Retention</h2>
        <p style={LS_P}>
          Your account and associated data (playlists, comments, ratings) are retained for as long as your account exists. You may request deletion at any time by contacting us. We will delete your data within 30 days of a verified request.
        </p>

        <h2 style={LS_H2}>6. Your Rights</h2>
        <p style={LS_P}>Depending on your location, you may have the right to:</p>
        <ul style={{ paddingLeft: 0, listStyle: 'none', marginBottom: 12 }}>
          {[
            'Access the personal data we hold about you',
            'Correct inaccurate data',
            'Request deletion of your data ("right to be forgotten")',
            'Object to or restrict certain processing',
            'Data portability (receive your data in a machine-readable format)',
          ].map((item, i) => (
            <li key={i} style={LS_LI}>
              <span style={{ position: 'absolute', left: 0, color: 'var(--accent)' }}>·</span>
              {item}
            </li>
          ))}
        </ul>
        <p style={LS_P}>To exercise any of these rights, contact us at <strong>privacy@aimusicstudio.fun</strong>.</p>

        <h2 style={LS_H2}>7. Children's Privacy</h2>
        <p style={LS_P}>
          AI Music Studio is not directed at children under 13. We do not knowingly collect personal information from anyone under 13. If you believe we have collected information from a child under 13, please contact us immediately.
        </p>

        <h2 style={LS_H2}>8. Changes to This Policy</h2>
        <p style={LS_P}>
          We may update this Privacy Policy from time to time. We will notify signed-in users of material changes via in-app notification. Continued use of the platform after changes constitutes acceptance of the updated policy.
        </p>

        <h2 style={LS_H2}>9. Contact</h2>
        <p style={{ ...LS_P, marginBottom: 0 }}>
          For privacy-related enquiries: <strong>privacy@aimusicstudio.fun</strong>
        </p>
      </LegalShell>
    </div>
  );
}

/* ============================================
   TERMS OF USE
   ============================================ */
function TermsScreen({ onBack }) {
  return (
    <div data-screen-label="Terms of Use">
      <LegalShell eyebrow="Legal" title="Terms of Use" lastUpdated="May 2026" onBack={onBack}>
        <p style={LS_P}>
          These Terms of Use govern your access to and use of AI Music Studio (the "Service"). By creating an account or using the Service, you agree to these Terms. If you do not agree, do not use the Service.
        </p>

        <h2 style={LS_H2}>1. Eligibility</h2>
        <p style={LS_P}>
          You must be at least 13 years old to use AI Music Studio. By using the Service, you represent that you meet this requirement. If you are under 18, you represent that your parent or legal guardian has reviewed and agreed to these Terms.
        </p>

        <h2 style={LS_H2}>2. Your Account</h2>
        <p style={LS_P}>
          You are responsible for maintaining the security of your account. We use Google Sign-In for authentication — we never store your password. You are responsible for all activity that occurs under your account. Notify us immediately at <strong>support@aimusicstudio.fun</strong> if you suspect unauthorised use of your account.
        </p>

        <h2 style={LS_H2}>3. Acceptable Use</h2>
        <p style={LS_P}>You agree not to:</p>
        <ul style={{ paddingLeft: 0, listStyle: 'none', marginBottom: 12 }}>
          {[
            'Post comments that are abusive, harassing, defamatory, or illegal',
            'Impersonate any person or entity',
            'Use the Service for any commercial purpose without our prior written consent',
            'Attempt to circumvent or disable any security feature',
            'Use automated tools (bots, scrapers) to access the Service',
            'Upload, stream, or reproduce music from this platform without authorisation',
            'Interfere with the proper operation of the Service',
          ].map((item, i) => (
            <li key={i} style={LS_LI}>
              <span style={{ position: 'absolute', left: 0, color: 'var(--danger, #f87171)' }}>·</span>
              {item}
            </li>
          ))}
        </ul>

        <h2 style={LS_H2}>4. Intellectual Property</h2>
        <p style={LS_P}>
          All music, recordings, artwork, and audio content on this platform are owned by Sasha and/or AI Music Studio and are protected by copyright law. You may not reproduce, distribute, publicly perform, or create derivative works from any content on this platform without explicit written permission.
        </p>
        <p style={LS_P}>
          AI-generated components of tracks do not diminish the copyright protection of the overall composition where a human author has made sufficient creative contribution.
        </p>

        <h2 style={LS_H2}>5. User-Generated Content</h2>
        <p style={LS_P}>
          Comments and other content you post ("User Content") remain yours. By posting User Content, you grant AI Music Studio a non-exclusive, worldwide, royalty-free licence to display, reproduce, and moderate that content on the platform. You represent that your User Content does not violate any third-party rights.
        </p>
        <p style={LS_P}>
          We reserve the right to remove any User Content that violates these Terms or is otherwise objectionable, without notice.
        </p>

        <h2 style={LS_H2}>6. DMCA / Copyright Notices</h2>
        <p style={LS_P}>
          If you believe content on AI Music Studio infringes your copyright, please send a DMCA takedown notice to <strong>dmca@aimusicstudio.fun</strong> including: (i) identification of the copyrighted work; (ii) identification of the infringing material and its location; (iii) your contact information; (iv) a statement of good faith belief; (v) a statement of accuracy under penalty of perjury; and (vi) your signature.
        </p>

        <h2 style={LS_H2}>7. Termination</h2>
        <p style={LS_P}>
          We may suspend or terminate your account at any time, with or without notice, if you violate these Terms or engage in conduct we determine to be harmful to the Service, other users, or third parties. You may delete your account at any time via your profile settings or by contacting us.
        </p>

        <h2 style={LS_H2}>8. Disclaimer of Warranties</h2>
        <p style={LS_P}>
          The Service is provided "as is" and "as available" without warranties of any kind, express or implied. We do not warrant that the Service will be uninterrupted, error-free, or free of harmful components. Your use of the Service is at your sole risk.
        </p>

        <h2 style={LS_H2}>9. Limitation of Liability</h2>
        <p style={LS_P}>
          To the maximum extent permitted by law, AI Music Studio and its operators shall not be liable for any indirect, incidental, special, consequential, or punitive damages arising from your use of, or inability to use, the Service. Our total liability for any claim arising under these Terms shall not exceed the amount you have paid us in the 12 months prior to the claim (if any).
        </p>

        <h2 style={LS_H2}>10. Changes to These Terms</h2>
        <p style={LS_P}>
          We may revise these Terms from time to time. We will notify you of material changes via in-app notification. Your continued use of the Service after changes take effect constitutes acceptance of the revised Terms.
        </p>

        <h2 style={LS_H2}>11. Governing Law</h2>
        <p style={{ ...LS_P, marginBottom: 0 }}>
          These Terms are governed by applicable law. Any dispute arising from these Terms shall be resolved by binding arbitration, except that either party may seek injunctive relief in a court of competent jurisdiction.
        </p>
      </LegalShell>
    </div>
  );
}

/* ============================================
   CONTACT
   ============================================ */
function ContactScreen({ onBack }) {
  const toast = useToast();
  const [name, setName]       = React.useState('');
  const [email, setEmail]     = React.useState('');
  const [subject, setSubject] = React.useState('general');
  const [message, setMessage] = React.useState('');
  const [sent, setSent]       = React.useState(false);
  const [sending, setSending] = React.useState(false);

  const SUBJECTS = [
    { value: 'general',   label: 'General enquiry'      },
    { value: 'support',   label: 'Support / bug report'  },
    { value: 'dmca',      label: 'Copyright / DMCA'      },
    { value: 'business',  label: 'Business & licensing'  },
    { value: 'press',     label: 'Press & media'         },
  ];

  const EMAILJS_SERVICE  = 'service_p3wia0o';
  const EMAILJS_TEMPLATE = 'template_xz8z49a';

  const handleSend = async () => {
    if (!name.trim() || !email.trim() || !message.trim()) {
      toast('Please fill in all fields', 'info'); return;
    }
    setSending(true);
    const subjectLabel = SUBJECTS.find(s => s.value === subject)?.label || subject;
    const entry = {
      name: name.trim(), email: email.trim(),
      subject: subjectLabel, message: message.trim(),
      timestamp: new Date().toISOString(),
      status: 'new',
    };

    let emailSent = false;

    // 1. Send email via EmailJS
    try {
      await window.emailjs.send(EMAILJS_SERVICE, EMAILJS_TEMPLATE, {
        from_name:  entry.name,
        from_email: entry.email,
        subject:    entry.subject,
        message:    entry.message,
        reply_to:   entry.email,
      });
      emailSent = true;
    } catch(e) {
      console.warn('EmailJS failed:', e);
    }

    // 2. Save to Firestore for record-keeping (best-effort)
    try {
      if (window.firestoreDB && window.firestoreModule) {
        const { collection, addDoc } = window.firestoreModule;
        await addDoc(collection(window.firestoreDB, 'contacts'), entry);
      }
    } catch(e) { /* non-critical */ }

    // 3. Fallback: open mailto if EmailJS also failed
    if (!emailSent) {
      const mailto = 'mailto:hello@aimusicstudio.fun?subject=' + encodeURIComponent(subjectLabel) + '&body=' + encodeURIComponent('Name: ' + entry.name + '\nEmail: ' + entry.email + '\n\n' + entry.message);
      window.open(mailto, '_blank');
    }

    setSent(true);
    toast("Message sent — we'll be in touch soon", 'success');
    setSending(false);
  };

  return (
    <div data-screen-label="Contact">
      <div style={{ maxWidth: 720, margin: '0 auto', paddingBottom: 'var(--space-7)' }}>
        {onBack && (
          <button className="btn btn-glass btn-sm" style={{ marginBottom: 'var(--space-4)' }} onClick={onBack}>
            <Icon name="arrow-left" size={14} /> Back
          </button>
        )}
        <div className="glass" style={{ padding: 'var(--space-6)', marginBottom: 'var(--space-4)' }}>
          <div className="eyebrow">Get in touch</div>
          <h1 className="h1" style={{ fontSize: 36, marginTop: 8 }}>Contact Us</h1>
          <div className="fg-2" style={{ fontSize: 14, marginTop: 8 }}>
            We read every message. Average response time: 1–2 business days.
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 'var(--space-4)' }}>
          {/* Left — contact info */}
          <div className="col gap-3">
            {[
              { icon: 'mail',   label: 'General',  value: 'hello@aimusicstudio.fun'   },
              { icon: 'shield', label: 'DMCA',     value: 'dmca@aimusicstudio.fun'    },
              { icon: 'lock',   label: 'Privacy',  value: 'privacy@aimusicstudio.fun' },
            ].map(item => (
              <div key={item.label} className="glass" style={{ padding: 'var(--space-4)' }}>
                <div className="row gap-3" style={{ alignItems: 'center' }}>
                  <div style={{ width: 38, height: 38, borderRadius: 10, background: 'var(--accent-soft)', color: 'var(--accent)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                    <Icon name={item.icon} size={16} />
                  </div>
                  <div className="col">
                    <div className="eyebrow" style={{ fontSize: 9, marginBottom: 2 }}>{item.label}</div>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{item.value}</div>
                  </div>
                </div>
              </div>
            ))}
            <div className="glass" style={{ padding: 'var(--space-4)', lineHeight: 1.6 }}>
              <div className="eyebrow" style={{ marginBottom: 8 }}>Response times</div>
              <div className="fg-2" style={{ fontSize: 12 }}>General &amp; support: 1–2 days</div>
              <div className="fg-2" style={{ fontSize: 12 }}>DMCA notices: 48 hours</div>
              <div className="fg-2" style={{ fontSize: 12 }}>Business &amp; press: 3–5 days</div>
            </div>
          </div>

          {/* Right — form */}
          <div className="glass" style={{ padding: 'var(--space-5)' }}>
            {sent ? (
              <div className="col gap-4" style={{ alignItems: 'center', textAlign: 'center', padding: 'var(--space-5) 0' }}>
                <div style={{ fontSize: 48 }}>✅</div>
                <div className="h3">Message received</div>
                <div className="fg-2" style={{ fontSize: 14 }}>
                  Thanks for reaching out. We'll get back to you at <strong>{email}</strong> within 1–2 business days.
                </div>
                <button className="btn btn-glass" onClick={() => { setSent(false); setName(''); setEmail(''); setMessage(''); setSubject('general'); }}>
                  Send another message
                </button>
              </div>
            ) : (
              <div className="col gap-4">
                <div className="row gap-3">
                  <div className="field" style={{ flex: 1 }}>
                    <label className="field-label">Your name</label>
                    <input className="input" placeholder="Sasha" value={name} onChange={e => setName(e.target.value)} />
                  </div>
                  <div className="field" style={{ flex: 1 }}>
                    <label className="field-label">Email</label>
                    <input className="input" type="email" placeholder="you@email.com" value={email} onChange={e => setEmail(e.target.value)} />
                  </div>
                </div>
                <div className="field">
                  <label className="field-label">Subject</label>
                  <select className="input" value={subject} onChange={e => setSubject(e.target.value)} style={{ cursor: 'pointer' }}>
                    {SUBJECTS.map(s => <option key={s.value} value={s.value}>{s.label}</option>)}
                  </select>
                </div>
                <div className="field">
                  <label className="field-label">Message</label>
                  <textarea
                    className="input"
                    placeholder="Tell us what's on your mind…"
                    rows={5}
                    value={message}
                    onChange={e => setMessage(e.target.value)}
                    style={{ minHeight: 120, resize: 'vertical' }}
                  />
                </div>
                <button
                  className="btn btn-primary btn-block"
                  onClick={handleSend}
                  disabled={sending || !name.trim() || !email.trim() || !message.trim()}
                >
                  {sending ? 'Sending…' : 'Send message'}
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AboutScreen, PrivacyScreen, TermsScreen, ContactScreen, FooterLinks });
